简体   繁体   中英

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

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

There is no function from laravel to run this out of the box.

You have to join this manually:

$pets = Pet::leftJoin('pet_user', function($join) use ($userId){
        $join->on('pets.id', '=', 'pet_user.pet_id');
        $join->on('pet_user.user_id', '=', \DB::raw("'".$userId."'"));
    })->whereNull('pet_user.pet_id')->get();

i would suggest this method if you already defined ManyToMany relationship on your models :

$user = User::find($user_id);
$pets = new Pet;
$exception = $user->profile->pluck('id')->toArray();
$pets = $pets->whereNotIn('id',$exception)->get();

My Solution: worked for me atleast.

Just use:

Pet::whereDoesntHave('user');

or

Pet::whereDoesntHave('user', function($qu) {
   // ...(extended query filter logic)
});

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