問題描述
在 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.
這篇關于Laravel/Eloquent : hasManyThrough WHERE的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!