I have a many to many relationship between users and books. How to select all books, that are not attached to a specific user?
The easy, but ugly, way is to load all books, load all books attached to the user and diff the collections. But there has to be an elegant way, I just can not figure it out.
It could be done using the query builder and a some joining, but how to achieve it using eloquent?
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
In pure SQL, we would use the IS NOT NULL condition, and the query would look like this: SELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .
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.
BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.
You can use whereDoesntHave()
for that:
$userId = 1;
$books = Book::whereDoesntHave('users', function($q) use ($userId){
$q->where('user_id', $userId);
})->get();
This method allows you to filter the query by the existence (whereHas
) (or in this case non-existence: whereDoesntHave
) of a related model.
In case you want all books that aren't assigned to any user it's a bit simpler:
$books = Book::doesntHave('users')->get();
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