Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从集合中查询关系值_Php_Laravel_Collections_Eloquent_Relationship - Fatal编程技术网

Php 从集合中查询关系值

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循环不是最佳方式,尽管我

我有3个表格,用户>帖子>评论。用户有很多帖子,帖子有很多评论。我试图只从用户那里获得评论。大概是这样的:

$user->posts->comments->where(...)->get()
  • $user->posts
    返回帖子集合
  • 因此,如果我尝试
    $user->posts->first()->comments
    ,它将返回post注释的集合
但是,对于上述场景(
posts->comments
),它不起作用,因为posts是一个集合

我相信运行for循环不是最佳方式,尽管我相信它可以通过这种方式实现


实现这一点的Laravel方法是什么?

您可以使用多种方法,请参阅

在您的用户模型中:

public function comments()
{
    return $this->hasManyThrough('App\Comment', 'App\Post');
}

谢谢!真不敢相信我错过了