【问题标题】:Laravel Eloquent: Looping through nested relationshipLaravel Eloquent:循环嵌套关系
【发布时间】:2021-03-06 19:31:25
【问题描述】:

这是我的人际关系:

User hasMany licences

Licence belongsTo User
Licence hasMany attestations

Attestation belongsTo Licence
Attestation hasMany vehicles

Vehicle belongsTo Attestation

例子:

用户
id | name
1 | John Doe

许可证
id | user_id | type
1 | 1 | A
2 | 1 | B

证明
id | licence_id | date
1 | 1 | 2020-12-05
2 | 1 | 2021-02-14
3 | 2 | 2021-03-02

车辆
id | attestation_id | type
1 | 1 | car
2 | 1 | boat
3 | 2 | motorcycle
4 | 2 | truck
5 | 3 | plane
6 | 3 | train

这就是我目前所拥有的:

 User::whereHas('licences', function($query) use($search) {
      if (!empty($search['licence_type'])) {
         $query->where('type', $search['licence_type']);
      }

    $query->whereHas('attestations', function($query) use($search) {

        if (isset($search['vehicles'])) {
            foreach ($search['vehicles'] as $vehicle) {
                $query->whereHas('vehicles', function($query) use($search, $vehicle) { 
                    $query->where('type', $vehicle);
                }); 
            }   
        }   
    });
})->get();

现在在我的过滤器中,如果我搜索“汽车”,则会检索到用户。但是,如果我搜索“汽车和摩托车”或“汽车和飞机”,则不会检索到用户。
我希望查询搜索给定用户的所有证明。
我该怎么做?

【问题讨论】:

  • car AND motorcyclecar AND plane 具有不同的 attestation_id。您可能需要 orWhere 而不是 where。

标签: mysql laravel eloquent


【解决方案1】:

试试这个

User::whereHas('licences', function($query) use($search) {
  if (!empty($search['licence_type'])) {
     $query->where('type', $search['licence_type']);
  }

  $query->whereHas('attestations', function($query) use($search) {
    if (isset($search['vehicles'])) {
        $query->whereHas('vehicles', function($query) use($search, $vehicle) { 
            $query->whereIn('type', $search['vehicles']);
        }); 
    }   
  });
})->get();

【讨论】:

  • 谢谢,但 whereIN 使用 OR 运算符,而我需要 AND 运算符。
猜你喜欢
  • 1970-01-01
  • 2016-06-11
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2017-10-17
  • 2017-12-13
  • 2020-04-04
相关资源
最近更新 更多