kodfire
kodfire

Reputation: 1783

Laravel - whereDoesntHave in nested relations

I'm running:

$products->whereDoesntHave('user.trainer');

The query that laravel makes is:

select *
from `products`
where not exists (
    select * from `users` where `products`.`user_id` = `users`.`id` and
    exists (
        select * from `trainers` where `users`.`id` = `trainers`.`user_id`
    )
)

While I want is:

select *
from `products`
where exists (  /* <---- */
    select * from `users` where `products`.`user_id` = `users`.`id` and
    not exists ( /* <---- */
        select * from `trainers` where `users`.`id` = `trainers`.`user_id`
    )
)

How can I achieve it?

Upvotes: 1

Views: 936

Answers (1)

Qirel
Qirel

Reputation: 26450

You can chain whereHas() with doesntHave() to retrieve the products where there is a users-relation that doesn't have a trainer.

$products->whereHas('user', function($query) {
    return $query->doesntHave('trainer');
});

Upvotes: 1

Related Questions