laravel - Eloquent 中的多对多和一对多关系
问题描述
我有三个表:“信使”通过一对多关系与“响应”连接(1 个信使可能有很多响应),以及通过多对多关系与“信使”连接的“结构”我想要在“reponses”表中查找连接到某个结构并且没有响应的信使。例如,对于在“结构”中标识为 1 的结构“DMO”,我希望找到属于该结构且未出现在“响应”中的信使。我正在使用 Laravel 8,我想用 Eloquent ORM 做到这一点。我正在尝试这个
public function dmoDG()
{
$structure = Structure::find(1);
$cou = $structure->courriers;
$courr = $cou->where('repondre','=',1)-
>where('dmo_sec','<>',NULL);
$courriers = $courr->doesntHave('reponses')->get();
return view("DG\dmoDG", compact('courriers'));
}
方法 Illuminate\Database\Eloquent\Collection::doesntHave 不存在。
解决方案
当您使用$model->relation
时,它会获取所有相关记录并将它们作为集合返回。
如果要在关系上使用查询构建器,则需要将其用作方法:$model->relation()
因此,如果您将关系作为属性访问,您将获得 Collection。但是,如果您将关系作为一种方法访问,您将获得查询构建器并在其上添加您的 where 子句。
在你的例子中;
public function dmoDG()
{
$structure = Structure::find(1);
// $cou = $structure->courriers; // for using without parentheses you got a collection, not a query builder
$cou = $structure->courriers(); // now you will have a query builder and Where clauses will work on this
$courr = $cou->where('repondre', '=', 1)->where('dmo_sec', '<>', NULL);
$courriers = $courr->doesntHave('reponses')->get();
return view("DG\dmoDG", compact('courriers'));
}
实际上,您可以将它们通过管道连接到一个衬里:
public function dmoDG()
{
$structure = Structure::find(1);
$courriers = $structure->courriers()->where('repondre', '=', 1)->where('dmo_sec', '<>', NULL)->doesntHave('reponses')->get();
return view("DG\dmoDG", compact('courriers'));
}
确保正确指定您的关系和列名。
推荐阅读
- android - Android Emulator WebView 上的 ERR_SSL_VERSION_OR_CIPHER_MISMATCH
- python - 使用 Flask Pymysql 提供图像“GET”请求,错误显示需要类似字节的对象,而不是 'dict'
- mouseevent - mouseReleased 和 mouseClicked 的区别
- reactjs - 在 POST/PUT/DELETE API 调用后更新 redux 存储中数据的最佳方法是什么
- video - raspi 无法加载视频的 Cobalt 调试版本
- java - 从数据库生成模型类
- php - Laravel hasManyThrough a different model
- html - 拒绝应用样式,因为它的 MIME 类型“text/html”不支持样式表 MIME 类型,并且启用了严格的 MIME 检查
- leaflet - 在完全相同的位置上带有多个标记的传单地图
- react-native - 实时重新加载后 AsyncStorage 回调不起作用