简体   繁体   中英

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM