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?
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.
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.
Invert your constraint, and pass the desired count to the whereHas
method:
Song::whereHas('writers', function() {
$query->where('writerField', false);
}, '=', 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With