Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: Get not related items in a many to many relation

Is it possible to get all items not related to the specific instance, in a many to many relation in Laravel?

Example:

I have two models, User and Pet. They have a many to many relationship, because a User can have many pets, but a pet can belong to more users.

But I want a list of pets, which a specific user is not having.

How is that possible?

EDIT The above is just an example, so not related to my current task. Just more simple to explain with users and pets. But to specify:

PETS TABLE:
ID TYPE
1  Dog
2  Cat
3  Rabit
4  Horse
5  Rat
6  Bat
7  Bird

USERS TABLE:
ID NAME
1  Martin
2  Peter
3  Viggo

PET_USER TABLE:
ID PET USER
1  1   1
2  3   1
3  5   1

Then Martin has a dog, a rabbit and a rat.

But I want a list of pets, that he does not have: Cat, horse, bat and bird

like image 855
mschadegg Avatar asked Feb 20 '16 20:02

mschadegg


1 Answers

You may try this (your question sounds a little confusing to me tho):

$pets = Pet::with('users')->whereDoesntHave('users', function($query) use ($id) {
    $query->where('users.id', $id);
})->get();

Also, try this as well (if you want):

$pets = Pet::with('users')->whereHas('users', function($query) use ($id) {
  $query->where('users.id', '!=', $id);
})->get();
like image 134
The Alpha Avatar answered Oct 23 '22 01:10

The Alpha