Raf*_*ski 2 php sql orm laravel eloquent
我在 Eloquent 中有以下模型:组、线程、评论和用户。我想从特定用户中查找特定组中的所有评论。
这是我目前的方法:
$group->threads->each(function ($thread) use ($user_id)
{
$user_comments = $thread->comments->filter(function ($comment) use ($user_id)
{
return $comment->owner_id == $id;
});
});
Run Code Online (Sandbox Code Playgroud)
这看起来很丑陋,可能很慢,我只想摆脱它。在 Eloquent 中获得我的结果集的最快和最优雅的方式是什么?
如果一个grouphasManythreads和一个threadhasMany comments,你可以添加另一个关系到组:grouphasManycomments到threads。
在小组:
public function comments() {
return $this->hasManyThrough('Comment', 'Thread');
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以通过以下方式获取组中的评论 $group->comments;
从这里,您可以满足用户的要求:
$user_comments = $group->comments()->where('owner_id', $user_id)->get();
Run Code Online (Sandbox Code Playgroud)
如果需要,您可以将 where out 提取到 Comment 的范围中。
| 归档时间: |
|
| 查看次数: |
18068 次 |
| 最近记录: |