我有这个:
$commentReplies = Comment::whereIn('comment_parent_id', $CommentsIDs)
->take(2)->get();
其中$CommentsIDs
是3个父注释id(1,2,3)的数组。
我试图为每个$ commentsID检索2个回复(如果它们存在)。 因此,如果回复存在,则总共有6个回复(每个评论2个)应该返回,仅此而已。但是,在那里使用take(2),它将回复限制为2,并且我们只得到其中一条评论的2个回复。 如何设置以最有效的方式为每个评论ID获得2个回复,以及如何在视图中使用正确的嵌套呈现它们?
类似的东西:
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)
更新
这是评论模型:
class Comment extends BaseModel {
public function latestTwoComments()
{
return $this->hasMany('Comment','comment_parent_id')->latest()->nPerGroup('comment_parent_id', 2);
}
}
查询:
$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)
答案 0 :(得分:10)
在急切加载时,您无法使用limit
/ skip
,因为这会限制整个相关结果。
我想你使用 MySQL ,所以这就是你需要的:http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/
这是很长时间粘贴到这里的方法,所以只是为了得到这个想法:你需要MySQL变量来为你做每个父母的n,例如:
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
注意:它适用于hasMany
关系和 MySQL