Php 从集合中查询关系值
我有3个表格,用户>帖子>评论。用户有很多帖子,帖子有很多评论。我试图只从用户那里获得评论。大概是这样的:Php 从集合中查询关系值,php,laravel,collections,eloquent,relationship,Php,Laravel,Collections,Eloquent,Relationship,我有3个表格,用户>帖子>评论。用户有很多帖子,帖子有很多评论。我试图只从用户那里获得评论。大概是这样的: $user->posts->comments->where(...)->get() $user->posts返回帖子集合 因此,如果我尝试$user->posts->first()->comments,它将返回post注释的集合 但是,对于上述场景(posts->comments),它不起作用,因为posts是一个集合 我相信运行for循环不是最佳方式,尽管我
$user->posts->comments->where(...)->get()
返回帖子集合$user->posts
- 因此,如果我尝试
,它将返回post注释的集合$user->posts->first()->comments
posts->comments
),它不起作用,因为posts是一个集合
我相信运行for循环不是最佳方式,尽管我相信它可以通过这种方式实现
实现这一点的Laravel方法是什么?您可以使用多种方法,请参阅 在您的用户模型中:
public function comments()
{
return $this->hasManyThrough('App\Comment', 'App\Post');
}
谢谢!真不敢相信我错过了