Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: How to select not attached records in many to many relationship?

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?

like image 706
rootman Avatar asked Feb 18 '15 13:02

rootman


People also ask

What is the use of whereHas in Laravel?

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

IS NOT NULL in Laravel eloquent?

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 .

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 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.


1 Answers

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();
like image 135
lukasgeiter Avatar answered Oct 16 '22 20:10

lukasgeiter