我有三个模型,即用户、帖子和评论
。
用户表
id username active
1 guyd 1
2 mohok 0
3 cotra 0
帖子表
id post_content user_id
1 Hello 1
2 World 2
3 Foo 3
评论表
id post_id user_id commment_body
1 1 2 Great post
2 1 3 Totally disagree
3 2 1 Nice read
4 2 3 Wow
5 1 1 Thanks guys
我的帖子模型有
public function latestComments($limit = 3)
{
return $this->hasMany(Comment::class)
->where('voided', '=', 0)
->with('user')
->join('users as comment_owner', 'comments.user_id', '=', 'comment_owner.id')
->where('comment_owner.active', '=', 1)
->orderByDesc('comments.updated_at')
->limit($limit);
}
我的评论模型有
public function user()
{
return $this->belongsTo(User::class);
}
我只想获取 active=1 的用户的帖子和评论。我正在使用以下内容,但它给出了错误的结果。它将评论分配给没有评论的帖子。
$posts = Post::orderBy('posts.created_at', 'DESC')
->with('user')
->with('latestComments')
->join('users as post_owner', 'posts.user_id', '=', 'post_owner.id')
->where('active', 1)
->paginate(5);
最佳答案
您应该使用whereHas()
Post::latest()
->with('user', 'latestComments')
->whereHas('user', function ($q) {
$q->where('active', 1);
})
->paginate(5);
如果您还想过滤评论:
->with(['user', 'latestComments' => function ($q) {
$q->whereHas('user', function ($q) {
$q->where('active', 1);
});
}])
关于Laravel 仅为活跃用户选择帖子和评论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48852055/