通过与Laravel和Eloquent的关系来统计和排序

时间:2022-03-16 20:17:59

How can I use Eloquent to count the number of comments from a post and order the posts by number of comments?

如何使用Eloquent计算帖子中的评论数量并按评论数量订购帖子?

My code is something like this:

我的代码是这样的:

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

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

I need to retrieve a collection of posts ordered by number of comments in an elegant way, thus I would prefer not to use something like 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));

我需要以优雅的方式检索按评论数量排序的帖子集合,因此我宁愿不使用类似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 个解决方案

#1


3  

You can use withCount to retrieve relation count and order it with orderBy(*_count). Something like,

您可以使用withCount检索关系计数并使用orderBy(* _ count)对其进行排序。就像是,

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

#1


3  

You can use withCount to retrieve relation count and order it with orderBy(*_count). Something like,

您可以使用withCount检索关系计数并使用orderBy(* _ count)对其进行排序。就像是,

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