简体   繁体   English

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

[英]Laravel multiple where clause in a whereHas constrain on a hasMany relationship

I have the following query...我有以下查询...

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

I want to get $pgcs with licences that fulfill the above conditions, the whereDate works correctly, but where('renewal', 0) doesn't seem to work correctly.我想获得具有满足上述条件的许可证的 $pgcs, whereDate 可以正常工作,但是 where('renewal', 0) 似乎不能正常工作。 The above query gets $pgcs with licences that have renewal that is = 1 as well, although same $pgc also have licences with renewal value of 0 and another with 1, I don't want a $pgc that has any licence with renewal value of 1 to be retrieved in this query.上面的查询得到 $pgcs 的许可证的续订也是 = 1,虽然相同的 $pgc 也有续订值为 0 的许可证和另一个具有 1 的许可证,但我不想要一个具有任何续订价值的许可证的 $pgc 1 要在此查询中检索。 what do I do?我该怎么办?

your cases are你的情况是

  • [1] pgc.. has two or more licences with renewal 0, 1 [1] pgc.. 有两个或多个续订 0、1 的许可证
  • [2] pgc.. has two or more licences with renewal 0, 0 [2] pgc.. 有两个或多个许可证续订 0, 0
  • [3] pgc.. has two or more licences with renewal 1, 1 [3] pgc.. 有两个或更多许可证续订 1, 1

right now your query is getting pgcs for cases [1],[2]现在您的查询正在获取案例 [1]、[2] 的 pgcs

so you have to alter your query logic a little, to only get [2]所以你必须稍微改变你的查询逻辑,才能得到 [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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM