Laravel 5.1-使用eloquent查询数据透视表
我正在使用Laravel5.1进行CMS开发。我有一个简单的帖子结构,用户和用户都可以喜欢帖子 帖子和用户有多对多关系,并使用数据透视表来表示关系 Posts模型已经Laravel 5.1-使用eloquent查询数据透视表,laravel,eloquent,laravel-5,Laravel,Eloquent,Laravel 5,我正在使用Laravel5.1进行CMS开发。我有一个简单的帖子结构,用户和用户都可以喜欢帖子 帖子和用户有多对多关系,并使用数据透视表来表示关系 Posts模型已经 public function likedby() { return $this->belongsToMany('App\Models\User','user_like_post') ->withTimestamps(); } public function likes(){ retu
public function likedby()
{
return $this->belongsToMany('App\Models\User','user_like_post')
->withTimestamps();
}
public function likes(){
return $this->belongsToMany('App\Models\Post','user_like_post')
->withTimestamps();
}
用户模型
public function likedby()
{
return $this->belongsToMany('App\Models\User','user_like_post')
->withTimestamps();
}
public function likes(){
return $this->belongsToMany('App\Models\Post','user_like_post')
->withTimestamps();
}
我想列出用户的最新活动。例如
mysql > select users.name, posts.heading from user_like_post as ulp
> join users on ulp.user_id=users.id
> join posts on ulp.post_id=posts.id
> order by ulp.created_at desc limit 10;
上面的查询工作正常,但有没有办法使用laravel eloquent来实现这一点?如果您想要纯eloquent解决方案,则需要为数据透视表添加其他模型:
类positionr扩展模型{
受保护的$table='user_like_post';
公共职能职位()
{
返回$this->belongsTo(Post::class);
}
公共函数用户()
{
返回$this->belongsTo(用户::类);
}
}
//然后像这样
$activity=posture::latest()->take(10)->get();
@foreach($activity作为$action)
{{$action->user->name}}喜欢{{{$action->post->title}
@endforeach
除此之外,您还需要联接
,以便按透视表对结果进行排序