问题描述
nofollow> hasManyThrough 。让我说我有名为Country,User,Post的模型。一个国家模型可能通过一个用户模型有很多帖子。这就是说,我只是可以打电话:
$ this-> hasManyThrough('Post','User','country_id' '用户名');
到目前为止这是很好的!
有人可以帮助吗?
所以这里:
模型: code>有许多
用户
有很多发布
这使我们可以像你的问题一样使用 hasManyThrough
//国家模型
public function posts()
{
return $ this-> hasManyThrough('Post','User','country_id','user_id');
}
您想要获得此关系的给定用户的帖子,因此: / p>
$ country = Country :: first();
$ country-> load(['posts'=> function($ q){
$ q-> where('user_id','=',3);
}]);
//或
$ country-> load(['posts'=> function($ q){
$ q-> has('user',function ){
$ q-> where('users.id','=',3);
});
})
$ country- >帖子; //收集与用户ID相关的帖子3
但是如果您使用这个代码,它会更容易,更可读和更有说服力:
(因为与查找id为3的用户的帖子与国家无关)
//用户模型
public function posts()
{
return $ this - >的hasMany( '邮政');
}
// then
$ user = User :: find(3);
// lazy load
$ user-> load('posts');
//或使用动态属性
$ user-> posts; //它会自动加载帖子
//或eager加载
$ user = User :: with('posts') - > find(3);
$ user-> posts; //给定用户的帖子收集
总结: hasManyThrough
是一种直接获取嵌套关系的方法,即。所有给定国家的帖子,而不是通过模型搜索具体的。
In the documentation of Eloquent it is said that I can pass the keys of a desired relationship to hasManyThrough.
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');
This is fine so far! But how can I get these posts only for the user with the id of 3 ?
Can anybody help here?
So here it goes:
models: Country
has many User
has many Post
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
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
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 / Enloft:hasManyThrough WHERE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!