如何使用 Eloquent 计算来自 post
的 comments
的数量,并根据 comments< 的数量对
?posts
进行排序
我的代码是这样的:
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 加入评论 posts.id = comments.post_id group by post.id order by count(post.id))
;
最佳答案
您可以使用 withCount
检索关系计数并使用 orderBy(*_count)
对其进行排序。类似的东西,
Post::withCount('comments')->orderBy('comments_count', 'desc')->get()
关于database - 根据与 Laravel 和 Eloquent 的关系进行计数和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222508/