whereHas 中的 Laravel 多个 where 子句约束 hasMany 关系

时间:2021-05-08 15:10:46

标签: mysql laravel eloquent

我有以下查询...

$pgcs = PrivateGuard::with(['licences', 'state'])
        ->whereHas('licences', function($query){
          $query->whereDate('expiration_of_licence', '<', Carbon::today())
                ->where('renewal', 0);
        })
        ->where('status', 1)
        ->get();

我想获得具有满足上述条件的许可证的 $pgcs,whereDate 工作正常,但 where('renewal', 0) 似乎无法正常工作。 上面的查询获取 $pgcs 的许可证,其续订值为 1,尽管相同的 $pgc 也有续订值为 0 的许可证和另一个值为 1 的许可证,但我不想要 $pgc 具有任何续订值的许可证要在此查询中检索的 1 个。我该怎么办?

1 个答案:

答案 0 :(得分:0)

您的案例是

  • [1] pgc .. 有两个或多个续订许可证 0 , 1
  • [2] pgc .. 有两个或多个续订许可证 0 , 0
  • [3] pgc .. 拥有两个或多个续订许可证 1 , 1

现在您的查询正在获取案例 [1],[2] 的 pgcs

所以你必须稍微改变你的查询逻辑,只得到 [2]

$pgcs = PrivateGuard::with(['licences', 'state'])
        ->whereHas('licences', function($query){
          $query->whereDate('expiration_of_licence', '<', Carbon::today())
                ->where('renewal', 0);
        })
        ->whereDoesntHave('licences', function($query){
          $query->where('renewal', 1);
        })
        ->where('status', 1)
        ->get();
相关问题