2014-07-25 41 views
0

我有一个与国家关系的用户。 (的hasMany)Laravel - 获取具有特定关系的用户

user_id 1 
country_id 1 

user_id 1 
country_id 2 

... 

我想要的是让那些谁拥有这两个国家(国家1和国家2)我怎么能这样做的用户?我正在阅读http://laravel.com/docs/eloquent#querying-relations,但我不知道该怎么办。

编辑:几乎解决

$users = \User::whereHas('countries', function($query) { 
    $countries_ids = [1, 2, 4]; 
    $query->whereIn('users_countries.country_id', $countries); 
})->get(); 

回答

3

这将工作的用户,只要):

$countries = [1,5,9]; 

User::whereHas('countries', function ($q) use ($countries) { 
    $q->whereIn('users_countries.country_id', $countries); 
}, '=', count($countries))->get(); 

如果有重复,如:

user_id | country_id 
    1 |  1 
    1 |  2 
    1 |  1 

那么你就需要生count(distinct ...),所以你不能使用whereHas,所以我的建议是,这将是更快:

$countries = [1,5,9]; 

User::join('users_countries as uc','uc.user_id', '=', 'users.id') 
    ->whereIn('uc.country_id', $countries) 
    ->having(DB::raw('count(distinct uc.country_id)'), '=', count($countries)) 
    ->groupBy('users.id') 
    ->get(['users.*']); 
+0

非常好!我只尝试了第一个,因为我没有重复。谢谢。 – Ulrira

+0

不客气。第二个解决方案在性能方面要好得多 - 没有依赖查询等 –

+0

@JarekTkaczyk你能帮我吗?http://stackoverflow.com/questions/35474941/how-to-get-the-max-id-in -a联接查询功能于laravel -5-诚信约束violati – Vikram

0

你可以做它的其他方式。在国家模型上进行查询。在国家模型中添加功能

public function user(){ 
    return $this->belongsTo('user');//or if there is no user_id column in the countries table, use the ('model','local_key','foreign_key') pattern. 
} 

然后用country_ids创建一个数组,然后使用country模型创建一个数组。

$country_ids=array(4,67); 
$countries=Country::where('id',$country_ids[0])->where('id',$country_ids[1])->get(); 

为了因为有数据透视表中没有重复(用于对例如FK键的唯一索引,让您应该遍历这样

foreach($countries->user as $user) 
+0

我不是100%肯定的结果,但你可以的var_dump ($国家),看看你得到什么。 –

+0

与“whereIn”方法,我会得到所有具有给定国家之一的用户,我想让所有国家给出 – Ulrira

+0

的用户您是对的。看我的编辑。你可以链接你的where()。翻译成WHERE的东西AND something_else –