Get all records from Model that do NOT have an ent

2019-05-28 10:07发布

问题:

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

回答1:

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