2014-06-24 36 views
2

在Eloquent的文档中,据说我可以将所需关系的关键字传递给hasManyThroughLaravel/Eloquent:hasManyThrough WHERE

可以说我有名为Country,User,Post的模型。国家模式可能通过用户模式有许多帖子。也就是说我可以打电话:

$this->hasManyThrough('Post', 'User', 'country_id', 'user_id'); 

这是很好的迄今! 但是,我怎样才能得到这些帖子只为ID为3的用户?

有人可以帮忙吗?

+0

在'User'模型上建立关系并获取您想要的用户的职位。或者使用'has'方法查询关系。或者使用查询生成器。请求精确的问题以获得准确的答案 –

+0

老实说,您的所有建议听起来都很有趣。我只是在寻找一种方法来实现这一点,不知道如何更精确地询问=( – user3518571

回答

2

所以这里有云:

型号: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模型。

+0

非常感谢!Btw:这个例子来自雄辩的文档站点,我完全同意你的看法! – user3518571

2
$user_id = 3; 

$country = Country::find($country_id); 

$country->posts()->where('users.id', '=', $user_id)->get();