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)

JavaScript

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

JavaScript

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

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement