使用Laravel和Eloquent计算和按关系排序

3

如何使用 Eloquent 统计一个帖子的评论数并按评论数对帖子进行排序?

我的代码大致如下:

class Post extends Model
{
    protected $table = 'posts';

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

我需要以优雅的方式检索评论数排序的帖子集合,因此我希望不要使用像DB::select(select count(comment.post_id), post.id from posts left join comments on posts.id = comments.post_id group by post.id order by count(post.id))这样的东西;

1个回答

5

您可以使用 withCount 来获取关联计数并使用 orderBy(*_count) 对其进行排序。就像这样,

Post::withCount('comments')->orderBy('comments_count', 'desc')->get()

谢谢,我使用了dd($posts)并注意到确实有一个名为comments_count的新属性。这正是我要找的。 - Alexandru Antochi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接