Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel whereDoesntHave() - multiple OR conditions

In Laravel 4.2 I have a model called Product with many-to-many relationshis to other models like Country or Category. I want to filter out products that are "incomplete", which means they have no connected countries or no connected categories. I can use whereDoesntHave() method to filter out one relation. When I use it two times in one query it creates AND condition, but I need OR. I can't find orWhereDoesntHave() method in API documentation. I can't pass multiple relations as arguments because it expects first argument to be a string.

I need something like this: $products = Product::whereDoesntHave('categories')->orWhereDoesntHave('countries')->get();

Is there any way to achive whereDoesntHave() with multiple OR conditions?

like image 975
KazikM Avatar asked Jan 21 '15 11:01

KazikM


People also ask

What is with () in Laravel?

with() function is used to eager load in Laravel. Unless of using 2 or more separate queries to fetch data from the database , we can use it with() method after the first command. It provides a better user experience as we do not have to wait for a longer period of time in fetching data from the database.

What is polymorphic relationship in Laravel?

A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.

What is belongsTo in Laravel?

BelongsTo relationship in laravel is used to create the relation between two tables. belongsTo means create the relation one to one in inverse direction or its opposite of hasOne. For example if a user has a profile and we wanted to get profile with the user details then we can use belongsTo relationship.


1 Answers

You can use doesntHave and specify the boolean operator:

$products = Product::doesntHave('categories')->doesntHave('countries', 'or')->get();

Actually you only need whereDoesntHave if you want to pass in a closure to filter the related models before checking if any of them exist. In case you want to do that you can pass the closure as third argument:

$products = Product::doesntHave('categories', 'or', function($q){
    $q->where('active', false);
})->doesntHave('countries', 'or')->get();
like image 180
lukasgeiter Avatar answered Sep 18 '22 17:09

lukasgeiter