Laravel - effectively limit every element of a child

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) 
+6
source share
1 answer

You cannot use limit / skip on active downloads, as this will limit all related output.

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

This is a way to insert here for a long time, so just to get an idea: you need MySQL variables to complete the job n for each parent for you, for example:

 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: this means the relationship between hasMany and MySQL

+9
source

Source: https://habr.com/ru/post/976396/


All Articles