Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel/Eloquent whereHas with all items in relation?

Models Song and Writer

And I want to query songs such that I only get songs where ALL its writers have a certain field that is true, what would my solution be?

The Laravel whereHas function will get all songs that have at least one writer with that field, like so.

Song::whereHas('writers', function($query){
    $query->where('writerField', '=', true);
});

But what is the pure eloquent way to make sure ALL writer related to a Song has that 'writerField' set to true?

like image 753
jamesmpw Avatar asked Sep 17 '15 20:09

jamesmpw


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.


1 Answers

Invert your constraint, and pass the desired count to the whereHas method:

Song::whereHas('writers', function() {
    $query->where('writerField', false);
}, '=', 0);
like image 97
Joseph Silber Avatar answered Nov 14 '22 21:11

Joseph Silber