laravel - 如何使用 wherePivot belongsToMany 关系添加多个条件
问题描述
我正在使用 Laravel 7。我有 3 张桌子
表格1
- ID
table_1_table_2
- id_table_1(fk 到 table_1)
- id_table_2(fk 到 table_2)
- 值(字符串)
- 隐藏(布尔)
表_2
- ID
所以我想要的是获取表中连接到table_1 中我的对象的所有条目。
所以我这样做了:
public function table2() {
return $this->belongsToMany(table_2,'table_1_table_2','id_table_1','id_table2')->withPivot(['value','hidden']);
}
效果很好。现在我只想要那些没有隐藏的人。所以我做了
public function table2NotHidden() {
return $this->belongsToMany(table_2,'table_1_table_2','id_table_1','id_table2')->wherePivot('hidden',0)->withPivot(['value','hidden']);
}
效果很好期待我在哪里需要它们,hidden == 0
但如果hidden == null
我尝试了一些类似的东西->where(function($query){...})
->wherePivot(function($query){...})
......但似乎没有任何效果。
解决方案
您可以尝试嵌套在哪里:
public function table2NotHidden() {
return $this->belongsToMany('table_2','table_1_table_2','id_table_1','id_table2')->
where(function($query){ $query->wherePivot('hidden',0)->orWherePivot('hidden',null);
});
}
或者您可以使用@Dilip Hirapara 解决方案:
->wherePivotIn('hidden', [0, null]);
return $this->belongsToMany(table_2,'table_1_table_2','id_table_1','id_table2')->where(function ($q) {
$q->orWhereNull('table_1_table_2.hidden')
->orWhere('table_1_table_2.hidden',0);
})
推荐阅读
- node.js - Api firebase 存储经过身份验证的用户 nodejs
- angular - 'unknown[]' 类型的参数不能分配给 > 'OperatorFunction 类型的参数
- azure - 如何在 azure devops 中将数组从变量组传递到 ARM 模板
- php - 付款后如何将Paypal交易和订单发送到数据库,Laravel 8
- javascript - 如何从本地存储项中命名 dexie db?
- swift - 访问和修改全局函数上的 @EnvironmentObject
- javascript - 如何从 XMLHttpRequest 获取数据到 GridView QML
- node.js - Bull 单独的进程超时,“作业停止超过允许的限制”
- incremental-build - 为什么 Shake 认为此文件已更改?
- exception - pjweekday 常量,用于多天的工作日异常