简体   繁体   中英

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. 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. what do I do?

your cases are

  • [1] pgc.. has two or more licences with renewal 0, 1
  • [2] pgc.. has two or more licences with renewal 0, 0
  • [3] pgc.. has two or more licences with renewal 1, 1

right now your query is getting pgcs for cases [1],[2]

so you have to alter your query logic a little, to only get [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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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