Php Laravel/雄辩:hasManyThrough在哪里

Php Laravel/雄辩:hasManyThrough在哪里,php,laravel,relational-database,eloquent,Php,Laravel,Relational Database,Eloquent,在Eloquent的文档中,据说我可以将所需关系的密钥传递给 假设我有名为Country、User、Post的模型。一个国家/地区模型可能通过一个用户模型有许多帖子。也就是说,我可以打电话: $this->hasManyThrough('Post', 'User', 'country_id', 'user_id'); 到目前为止还不错但是我如何才能仅为id为3的用户获取这些帖子? 有人能帮上忙吗?下面是: 型号:Country有许多User有许多Post 这允许我们在您的问题中使用has

在Eloquent的文档中,据说我可以将所需关系的密钥传递给

假设我有名为Country、User、Post的模型。一个国家/地区模型可能通过一个用户模型有许多帖子。也就是说,我可以打电话:

$this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
到目前为止还不错但是我如何才能仅为id为3的用户获取这些帖子?

有人能帮上忙吗?

下面是:

型号:
Country
有许多
User
有许多
Post

这允许我们在您的问题中使用
hasManyThrough

// Country model
public function posts()
{
  return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}
您希望获取此关系的给定用户的帖子,因此:

$country = Country::first();
$country->load(['posts' => function ($q) {
  $q->where('user_id', '=', 3);
}]);
// or
$country->load(['posts' => function ($q) {
  $q->has('user', function ($q) {
    $q->where('users.id', '=', 3);
  });
})

$country->posts; // collection of posts related to user with id 3

但是如果您改用此选项,将会更容易、更可读、更雄辩: (因为当你寻找id为3的用户的帖子时,它与国家无关)


总而言之:
hasManyThrough
是一种直接获取嵌套关系的方法,即给定国家的所有帖子,而不是通过
模型搜索特定的

$this->hasManyThrough('Post','User','country\u id','User\u id')->其中(x列)

$user_id = 3;

$country = Country::find($country_id);

$country->posts()->where('users.id', '=', $user_id)->get();

这里发生的事情是,你得到了收集,作为回报,你可以在最后设置你想要的任何条件。

User
模型上设置关系,并为你想要的用户获取帖子。或者使用
has
方法查询关系。或者使用查询生成器。。问精确的问题以得到准确的答案诚实地说,你所有的建议听起来都很有趣。我只是在寻找一种方法来实现这一点,不知道如何更精确地问=(非常感谢!顺便说一句:这个例子取自雄辩的文档网站。我完全同意你的观点!
$user_id = 3;

$country = Country::find($country_id);

$country->posts()->where('users.id', '=', $user_id)->get();