从模型获取所有在枢轴表Laravel 5中没有条目的记录 [英] Get all records from Model that do NOT have an entry in pivot table Laravel 5

查看:75
本文介绍了从模型获取所有在枢轴表Laravel 5中没有条目的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出如何实现以下目标.我已经搜索了,但搜索无济于事.

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

我在Laravel 5应用中有一个数据透视表,该数据透视表按预期工作,并且在各个模型中具有以下功能.

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');
}

我可以在Sitecontroller.php中检索类似以下内容的所有相关记录

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 )

先谢谢了. M

推荐答案

在这种情况下,应从Module端开始查询并用whereDoesntHave排除该问题:

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

这篇关于从模型获取所有在枢轴表Laravel 5中没有条目的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆