11

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

  • Post hasMany Comment
  • Comment belongsTo Post
  • CommentLike belongsTo User
  • CommentLike belongsTo Comment
  • Comment hasMany CommentLike

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.

Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
darkylmnx
  • 1,891
  • 4
  • 22
  • 36

2 Answers2

32

Try this

Post::with(['comments' => function($query){
   $query->withCount('likes');
}])->take(10)->get();
mgraph
  • 15,238
  • 4
  • 41
  • 75
A.khalifa
  • 2,366
  • 3
  • 27
  • 40
  • is there a way to get the total count of likes instead of the count per comment? Something to be able to get the via `$post->likes_count` or similar – fudo Dec 23 '20 at 14:32
  • Doesn't this require a `return` statement? – Dharman Sep 08 '22 at 09:56
  • 1
    @Dharman the query object (like all objects) is passed by reference, so the closure isn’t expected or needed to return anything in order to modify the object. – miken32 Sep 10 '22 at 03:55
0

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();