【发布时间】:2017-10-28 13:59:59
【问题描述】:
如何使用 Eloquent 从 post 中计算 comments 的数量,并按 comments 的数量排序 posts?
我的代码是这样的:
class Post extends Model
{
protected $table = 'posts';
public function comments()
{
return $this->hasMany('App\Comment');
}
}
我需要以一种优雅的方式检索按 cmets 数量排序的帖子集合,因此我不希望使用像 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)) 这样的东西;
【问题讨论】:
标签: database laravel eloquent relationship