mysql - Laravel orWhereIn 和 orWhereIn 等等
问题描述
老实说,我不知道如何描述我的查询问题,希望示例能够解决问题:
我有一个简单的查询:
return $query->whereHas('categories', function ($q) use ($ids) {
$q->whereIn('category_id', $ids);
}, '=', count($ids));
它返回与类别 ID 数组匹配的记录。为了更好地呈现这个现在我们有这样的条件
getRecordsThatMatchThisCondition(id1 && id2 && id3... and so on).
我想要的是实现这样的比较
getRecordsThatMatchThisCondition((id1.1 || id1.2 || id1.3) && (id2.1 || id2.2) ... and so on.)
到目前为止,我找不到任何有关此问题的帮助。即使命名这样的查询也会有所帮助。我的桌子很简单 PIVOT
id record_id category_id
------------------------------------
1 1 35
2 2 41
3 2 74
4 3 74
5 3 40
6 4 40
用文字总结我的问题:
我与所选类别的 parent_category 没有记录关系...现在我需要显示与多个类别匹配的所有记录。
可视化问题:
Record is assigned to categories like this:
35
└40
└41 ☑
36
└74 ☑
通过提供 id 35 和 36,应该可以找到记录!通过提供 40,不应找到74 ...
希望我已经很好地描述了我的问题。
解决方案
您不能使用whereIn
这样的方法进行查询,但可以使用 foreach 循环,如下所示:
return $query->whereHas('categories', function ($q) use ($ids) {
foreach($ids as $key => $value) {
$q->orWhere('category_id', $value)
}
}, '=', count($ids));
或者,使用for
循环:
return $query->whereHas('categories', function ($q) use ($ids) {
for ($i = 0; $i < count($ids); $i++){
$q->orWhere('category_id', $ids[$i]);
}
}, '=', count($ids));
推荐阅读
- php - 如何转换数组如下?
- python - 标准化:如何避免零标准偏差
- python - 如何检查两个列表在python中具有相同的值和相同的长度
- c# - 是否可以在 WCF 跟踪文件 (.svclog) 中记录异常“无法分配...的托管内存缓冲区”?
- go - 杜松子酒上的 router.Static() 和 router.Use(static.Serve()) 有什么区别?
- c# - asmx 服务返回 xml 而不是 json
- python - Python多级继承
- python - GroupBy 和更改一列的值
- mongodb - 用 TypeORM/MongoDB 中 ObjectIdColumn 的自定义字符串替换 ObjectId 字段
- assembly - 在汇编中打印整数的正确 SWI 语句是什么?