简体   繁体   中英

Get all records from Model that do NOT have an entry in pivot table Laravel 5

I am trying to figure out how to achieve the following. I have searched and searched to no avail.

I have a pivot table in a Laravel 5 app that is working as expected with the following functions in the respective models.

// Module.php
//...
public function sites()
{
    return $this->belongsToMany('App\Site')->withPivot('enabled');
}

// Site.php
//...
public function modules()
{
    return $this->belongsToMany('App\Module')->withPivot('enabled');
}

I can retrieve all relevant records with something like the following in my Sitecontroller.php

$site = Site::with('modules')->findOrFail($id);

The problem i have is i want to be able to get all modules that do not have an associated record in the pivot table for the site in question.

Can anyone point in the right direction how i might achieve something like this, in the right way ( i can think of a few ways but seems really hacky )

Thanks in advance. M

Starting the query from the Module side and excluding with whereDoesntHave should work in this case:

$id = 1;
$modules = Module::whereDoesntHave('sites', function($q) use ($id){
    $q->where('site_id', $id);
})->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