首页 > 解决方案 > Laravel 在 whereHas 中的多个 where 子句约束 hasMany 关系

问题描述

我有以下查询...

$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 要在此查询中检索。我该怎么办?

标签: mysqllaraveleloquent

解决方案


你的情况是

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

推荐阅读