Reputation: 1465
How can I use Eloquent to count the number of comments
from a post
and order the posts
by number of comments
?
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))
;
Upvotes: 3
Views: 3285
Reputation: 2894
You can use withCount
to retrieve relation count and order it with orderBy(*_count)
. Something like,
Post::withCount('comments')->orderBy('comments_count', 'desc')->get()
Upvotes: 6