Won*_*nka 7 laravel eloquent laravel-4
我有这个:
$commentReplies = Comment::whereIn('comment_parent_id', $CommentsIDs)
->take(2)->get();
Run Code Online (Sandbox Code Playgroud)
$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)
Run Code Online (Sandbox Code Playgroud)
更新:
这是评论模型:
class Comment extends BaseModel {
public function latestTwoComments()
{
return $this->hasMany('Comment','comment_parent_id')->latest()->nPerGroup('comment_parent_id', 2);
}
}
Run Code Online (Sandbox Code Playgroud)
查询:
$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)
Run Code Online (Sandbox Code Playgroud)
Jar*_*zyk 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
Run Code Online (Sandbox Code Playgroud)
注意:它适用于hasMany
关系和MySQL
归档时间: |
|
查看次数: |
1533 次 |
最近记录: |