I have it:
$commentReplies = Comment::whereIn('comment_parent_id', $CommentsIDs) ->take(2)->get();
Where $CommentsIDs is an array of 3 parent comment identifiers (1,2,3).
I am trying to get 2 responses for each of the $ commentsIDs if they exist. Thus, a total of 6 responses (2 for each comment) should be returned with a request, if answers exist, nothing more. However, with take (2) there it limits the responses to 2, and we get only 2 answers for one of the comments. How can I configure to get 2 responses for each of the comment identifiers in the most efficient way and how can they be displayed in a view with the correct nesting?
Sort of:
Comment 1 --Comment 1 Reply 1 (load this) --Comment 1 Reply 2 (load this) --Comment 1 Reply 3 (don't load this) --Comment 1 Reply 4 (don't load this) Comment 2 --Comment 2 Reply 1 (load this) --Comment 2 Reply 2 (load this) --Comment 2 Reply 3 (don't load this) Comment 3 (no replies, don't load anything)
Update:
Here is the comment model:
class Comment extends BaseModel { public function latestTwoComments() { return $this->hasMany('Comment','comment_parent_id')->latest()->nPerGroup('comment_parent_id', 2); } }
Query:
$comments = Comment::with('latestTwoComments')->get(); dd(DB::getQueryLog()); // Result: 'query' => string 'select * from (select `comments`.*, @rank := IF(@group = comment_parent_id, @rank+1, 1) as rank_575b053fb57f8fab5bc86dd324b39b91, @group := comment_parent_id as group_575b053fb57f8fab5bc86dd324b39b91 from (SELECT @rank:=0, @group:=0) as vars, comments where `comments`.`deleted_at` is null order by `comment_parent_id` asc, `created_at` desc) as comments where `comments`.`deleted_at` is null and `rank_575b053fb57f8fab5bc86dd324b39b91` <= ? and `comments`.`comment_parent_id` in (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?'... (length=603)