简体   繁体   English

从模型获取所有在枢轴表Laravel 5中没有条目的记录

[英]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. 我在Laravel 5应用程序中有一个数据透视表,该数据透视表按预期工作,并且在各个模型中具有以下功能。

// 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 我可以在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: 在这种情况下,从Module端开始查询,并使用whereDoesntHave排除是whereDoesntHave

$id = 1;
$modules = Module::whereDoesntHave('sites', function($q) use ($id){
    $q->where('site_id', $id);
})->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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