2017-06-17 162 views
0

你一定看过以下功能(在脸书上),一个帖子有一些评论,每个评论都有一个类似的计数器。雄辩计数嵌套的渴望加载嵌套关系

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

在laravel它会是这样的

  • 张贴的hasMany评论
  • 评论属于关联后
  • CommentLike属于关联用户
  • CommentLike属于关联评论
  • 评论的hasMany CommentLike

所以现在,我想10个职位与他们的意见,与根据注释等等计数器

邮政::与( '意见') - > withCount( 'comments.likes') - >取(10) - >的get();

这并不在所有的工作......

邮政::与( '意见') - > withCount( '意见') - >取(10) - >得到();

这样做,但这个计数每个帖子的所有评论,我想要计算每个帖子每个评论的所有喜欢。

回答

0

试试这个

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

这似乎并没有工作 – darkylmnx

0

我做一个假设CommentLike表示comment_likes

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

不错我会尽力的!但是没有“雄辩”的方式来做到这一点?没有原始查询? – darkylmnx

+0

不是我所知的总和(...)函数。 – btl