从模型中获取所有在数据透视表Laravel 5中没有条目的记录

时间:2015-02-20 21:12:40

标签: php mysql laravel pivot-table laravel-5

我想弄清楚如何实现以下目标。我搜索并搜索无济于事。

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

我可以使用我的Sitecontroller.php

中的以下内容检索所有相关记录
$site = Site::with('modules')->findOrFail($id);

我遇到的问题是我希望能够在相关网站的数据透视表中获取所有没有相关记录的模块。

任何人都可以指出正确的方向我将如何以正确的方式实现这样的目标(我可以想到一些方法,但看起来真的很hacky)

提前致谢。 中号

1 个答案:

答案 0 :(得分:6)

Module方面开始查询并使用whereDoesntHave排除在这种情况下应该有效:

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