最佳答案
在 Model 中定义需要获取的关系表字段 created_at
class User extends Authenticatable
{
.
.
.
public function followers()
{
return $this->belongsToMany(User::class,'followers','user_id', 'follower_id')
->withPivot('created_at')->withTimestamps();
}
public function followings()
{
return $this->belongsToMany(User::class,'followers','follower_id','user_id')
->withPivot('created_at')->withTimestamps();
}
.
.
.
}
在 Controller 中使用 $follower->pivot->created_at
获取该字段的值
class UsersController extends Controller
{
.
.
.
public function followers(User $user)
{
$users = $user->followers()->paginate(30);
foreach ($users as $follower) {
//获取关系表的创建时间字段 赋值给$users->follow_time 供前台使用
$follower->follow_time = $follower->pivot->created_at;
}
$title = '粉丝';
return view('users.show_follow',compact('users','title'));
}
.
.
.
}
文档:模型关联《Laravel 5.6 中文文档》 获取中间表字段
讨论数量:
@tooyond 是新手就不要这么暴躁,文档是说明书,告诉你如何调用laravel的函数,教程是实践,教你如何做出一个产品,两者都有存在的意义。你自己都说对文档不够熟悉,我让你去看文档的查表部分,你就去看
在 Model 中定义需要获取的关系表字段 created_at
class User extends Authenticatable
{
.
.
.
public function followers()
{
return $this->belongsToMany(User::class,'followers','user_id', 'follower_id')
->withPivot('created_at')->withTimestamps();
}
public function followings()
{
return $this->belongsToMany(User::class,'followers','follower_id','user_id')
->withPivot('created_at')->withTimestamps();
}
.
.
.
}
在 Controller 中使用 $follower->pivot->created_at
获取该字段的值
class UsersController extends Controller
{
.
.
.
public function followers(User $user)
{
$users = $user->followers()->paginate(30);
foreach ($users as $follower) {
//获取关系表的创建时间字段 赋值给$users->follow_time 供前台使用
$follower->follow_time = $follower->pivot->created_at;
}
$title = '粉丝';
return view('users.show_follow',compact('users','title'));
}
.
.
.
}
文档:模型关联《Laravel 5.6 中文文档》 获取中间表字段
推荐文章: