Laravel/Eloquent : hasManyThrough WHERE
在 Eloquent 的文档中,据说我可以将所需关系的键传递给 hasManyThrough.
In the documentation of Eloquent it is said that I can pass the keys of a desired relationship to hasManyThrough.
假设我有名为 Country、User、Post 的模型.通过用户模型,国家模型可能有许多帖子.也就是说,我可以直接调用:
Lets say I have Models named Country, User, Post. A Country model might have many Posts through a Users model. That said I simply could call:
$this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
到目前为止一切正常!但是我如何才能只为 id 为 3 的用户获取这些帖子?
有人可以帮忙吗?
推荐答案
就这样:
models: Country
有很多 User
有很多 Post
models: Country
has many User
has many Post
这允许我们在您的问题中使用 hasManyThrough
:
This allows us to use hasManyThrough
like in your question:
// Country model
public function posts()
{
return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}
您想获取此关系的给定用户的帖子,因此:
You want to get posts of a given user for this relation, so:
$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 的用户的帖子时,它与国家无关)
BUT it will be easier, more readable and more eloquent if you use this instead: (since it has nothing to do with country when you are looking for the posts of user with 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
模型.
To sum up: hasManyThrough
is a way to get nested relation directly, ie. all the posts for given country, but rather not to search for specific through
model.
相关文章