首页 > 解决方案 > 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 ...

希望我已经很好地描述了我的问题。

标签: mysqllaravellaravel-5eloquent

解决方案


您不能使用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));

推荐阅读