Skip to content
Advertisement

How to count related models when querying relationship existence via whereHas?

I have 2 models: Client model hasMany deposits_quantity(ClientDeposit)

class Client extends Model
{
  public function deposits_quantity()
  {
    return $this->hasMany(ClientDeposit::class, 'client_id');
  }
}

how can I get a specific quantity of related(deposits_quantity) model results without braking query ‘chaining’? suppose I have query chain like this:

$query = Client::query()

and for example i have filter that filters relation by creation date:

$query->whereHas('deposits_quantity', function($query) use($request)  {
  $query->whereDate('created_at', '>=', $request->input('deposit_at_from'))
  ->whereDate('created_at', '<=', $request->input('deposit_at_to')); })

and next when I trying to filter relation quantity like this to get only Clients with 2 deposits_quantity :

$query->has('deposits_quantity' ,'=', 2')

it returns Clients with 2 Deposits but it brakes the query chain and returns results from the beginning without all the filters before, it returns clean “has” and ignoring other filters, I know it because I call ‘has’, but how to do it right to get results by a specific quantity of relation and after filtering?

Advertisement

Answer

You may use 2nd and 3rd arguments of whereHas to specify an operator and count to further customize the query:

$query->whereHas('deposits_quantity', function($query) use ($request) {
    $query->whereDate('created_at', '>=', $request->input('deposit_at_from'))
          ->whereDate('created_at', '<=', $request->input('deposit_at_to'));
}, '=', 2) // <= Attention to these 2 arguments passed to `whereHas`
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement