darkylmnx
darkylmnx

Reputation: 2071

Eloquent Count nested relationships with nested eager loading

You must have seen the following feature (on facebook), a post with some comments, each comment has a like counter.

https://img4.hostingpics.net/pics/67853820170616003640LaravelNewsAccueil.png

In laravel it would be something like

So, now I want to get 10 posts with their comments, with the like counter per comment.

Post::with('comments')->withCount('comments.likes')->take(10)->get();

This does not work at all.

Post::with('comments')->withCount('comments')->take(10)->get();

This counts all comments for each post, I want to count all likes per comment on each post.

Upvotes: 13

Views: 14168

Answers (2)

A.khalifa
A.khalifa

Reputation: 2496

Try this

Post::with(['comments' => function($query){
   $query->withCount('likes');
}])->take(10)->get();

Upvotes: 38

user320487
user320487

Reputation:

I'm making an assumption CommentLike represents a comment_likes table

Post::with('comments' => function($query){
    $query->select('comment_likes.*')
          ->join('comments', 'comments.id', '=', 'comment_likes.comment_id')
          ->groupBy('comments.id')    
          ->havingRaw('sum(comment_likes.id) as likes')
}])->take(10)->get();

Upvotes: 0

Related Questions