【问题标题】:Laravel - Get an user who has specific relationshipsLaravel - 获取具有特定关系的用户
【发布时间】:2014-09-17 15:58:21
【问题描述】:

我有一个用户与国家关系。 (有很多)

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();

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    你可以用另一种方式来做。查询国家模型。在国家模型中添加一个函数

     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_ids=array(4,67);
     $countries=Country::where('id',$country_ids[0])->where('id',$country_ids[1])->get();
    

    为了获得用户,您应该像这样循环访问

    foreach($countries->user as $user)
    

    【讨论】:

    • 我不能 100% 确定结果,但你可以 var_dump($countries) 看看你得到了什么。
    • 使用“whereIn”方法,我将获得所有拥有给定国家之一的用户,我想获得拥有所有国家的用户
    • 你是对的。请参阅我的编辑。你可以链接你的 where()'s 。转化为 WHERE something AND something_else
    【解决方案2】:

    只要数据透视表中没有重复项(例如,一对 fk 键的唯一索引),这将起作用:

    $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.*']);
    

    【讨论】:

    • 非常好!我只尝试了第一个,因为我没有重复。谢谢。
    • 不客气。第二种解决方案在性能方面要好得多 - 没有依赖查询等
    • @JarekTkaczyk 你能帮我吗stackoverflow.com/questions/35474941/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 2016-05-16
    • 2022-01-08
    相关资源
    最近更新 更多