Laravel - Limit each child item efficiently

后端 未结 1 1521
-上瘾入骨i
-上瘾入骨i 2020-12-09 22:12

I have this:

$commentReplies = Comment::whereIn(\'comment_parent_id\', $CommentsIDs)
                                  ->take(2)->get();
1条回答
  •  长情又很酷
    2020-12-09 22:54

    You can't use limit/skip when eager loading, for it will limit whole related result.

    I suppose you use MySQL, so here is what you need: http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/

    It's way to long to paste here, so just to get the idea: You need MySQL variables to do the job of fetching n per parent for you, like:

    public function latestTwoComments()
    {
      return $this->hasMany('Comment', 'comment_parent_id')->latest()->nPerGroup('comment_parent_id', 2);
    }
    
    //then
    $comments = Comment::with('latestTwoComments')->get();
    // now all the comments will have at most 2 related child-comments
    

    Note: it's meant for hasMany relation and MySQL

    0 讨论(0)
提交回复
热议问题