A combination of Laravel has () and whereHas ()

I am trying to combine some methods in Eloquent but cannot seem to collect them correctly. I have a query that is pulling all items where the hasMany count is 0.

So basically I want to know where the relationship is "empty". In this case, I have an element with sound samples. So, I want to get items that have no sound samples yet.

return $this->hasMany('App\Models\Item')->has('audios', '=', 0);

      

This works great. However, I also want to add a filter based on male and female audio samples. If I use whereHas

, I can get the filter, but only directly, and I cannot get an offer has 0

on it.

return $this->hasMany('App\Models\Item')->whereHas('audios', function ($q) {
    $q->where('gender', 'female');
});

      

But I don't want to combine them and can't figure out what the bit is. So, "get all items without female audio samples".

Not a lot of documentation on these matters, except in a trivial case, I tried several options but it doesn't. Just completely empty sets or just a female or a male directly without this "empty" set of 0.

Here is the request I would like to receive:

SELECT *
FROM `items`
WHERE (
    SELECT COUNT(*) 
    FROM `audios`
    WHERE `audios`.`item_id` = `items`.`id`
    AND `audios`.`gender`='female'
) = 0

      

+3


source to share


1 answer


whereHas

, doesntHave

etc. - all methods that are ultimately called has

. If you look at the signature whereHas

, you will see that it also allows you to transfer an invoice:

public function whereHas($relation, Closure $callback, $operator = '>=', $count = 1)

      



So, you can do this, or just use whereDoesntHave

:

return $this->hasMany('App\Models\Item')->whereDoesntHave('audios', function ($q) {
    $q->where('gender', 'female');
});

      

+3


source







All Articles