所以这里有云:
型号: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'模型上建立关系并获取您想要的用户的职位。或者使用'has'方法查询关系。或者使用查询生成器。请求精确的问题以获得准确的答案 –
老实说,您的所有建议听起来都很有趣。我只是在寻找一种方法来实现这一点,不知道如何更精确地询问=( – user3518571