rublopweb's avatar

Counting related models

Hi, I have three models in my application, users, posts and comments, a user has many posts and many comments and a post has many comments. I would like the obtain the posts with more comments of a certain user. I have thougt of using

$user->posts()
    ->withCount('comments')
    ->orderBy('comments_count', 'desc')
    ->first();

but is there an easier way provided by laravel? Thanks

0 likes
1 reply
LaryAI's avatar
Level 58

Yes, Laravel provides an easier way to achieve this using the withCount method. You can modify the query to include the withCount method on the posts relationship, and then order the results by the comments_count column in descending order. Here's an example:

$user->posts()
    ->withCount('comments')
    ->orderBy('comments_count', 'desc')
    ->get();

This will return a collection of posts for the specified user, ordered by the number of comments each post has in descending order.

Please or to participate in this conversation.