按与 Laravel 和 Eloquent 的关系计数和排序

Ale*_*chi 3 database relationship laravel eloquent

如何使用洋洋洒洒数的数量commentspost和秩序posts的数量comments

我的代码是这样的:

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

    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要以优雅的方式检索按评论数量排序的帖子集合,因此我不想使用类似的东西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))

Cha*_*y22 5

您可以使用withCount来检索关系计数并使用orderBy(*_count). 就像是,

Post::withCount('comments')->orderBy('comments_count', 'desc')->get()
Run Code Online (Sandbox Code Playgroud)