我正试图弄清楚如何实现以下目标。我找了又找,都没有用。
我在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);
我遇到的问题是,我希望能够获得所有模块,这些模块在相关网站的数据透视表中没有相关记录。
有人能指出我如何以正确的方式实现这样的目标吗?
提前谢谢。M
在这种情况下,从Module
端启动查询并使用whereDoesntHave
排除应该有效:
$id = 1;
$modules = Module::whereDoesntHave('sites', function($q) use ($id){
$q->where('site_id', $id);
})->get();