[英]Laravel / Eloquent : hasManyThrough WHERE
在Eloquent的文档中,据说我可以将所需关系的键传递给hasManyThrough 。
假设我有名为Country,User,Post的模型。 国家/地区模型可能通过用户模型包含许多帖子。 那说我可以打电话:
$this->hasManyThrough('Post', 'User', 'country_id', 'user_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的用户的帖子时,它与国家无关)
// User model
public function posts()
{
return $this->hasMany('Post');
}
// then
$user = User::find(3);
// lazy load
$user->load('posts');
// or use dynamic property
$user->posts; // it will load the posts automatically
// or eager load
$user = User::with('posts')->find(3);
$user->posts; // collection of posts for given user
总结一下: hasManyThrough
是一种直接获得嵌套关系的方法,即。 给定国家的所有帖子,而不是through
模型搜索特定的。
$user_id = 3;
$country = Country::find($country_id);
$country->posts()->where('users.id', '=', $user_id)->get();
$this->hasManyThrough('Post', 'User', 'country_id', 'user_id')->where(column,x);
这里发生的是你得到的收集作为回报你可以在最后放置你想要的任何条件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.