【问题标题】:Laravel orWhereIn and orWhereIn and so onLaravel orWhereIn 和 orWhereIn 等等
【发布时间】:2020-08-10 12:11:31
【问题描述】:

老实说,我不知道如何描述我的查询问题,希望示例能够解决问题:

我有一个简单的查询:

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...

希望我已经充分描述了我的问题。

【问题讨论】:

  • 为什么要做这种条件?
  • @MrEduar 嗯...长话短说。我有一个绝妙的主意,不要将所有关系都保存到类别中。换句话说,我只保存用户选择的类别树上的最低类别。但是现在我需要创建“混合类别”,它显示与用户提供的 ALL 类别匹配的所有记录。然而简单的 whereIn 是不够的,因为如果记录属于(查看我提供的树) category_id: 41,并且混合类别绑定到 35,我将找不到这样的记录。要找到这条记录,我必须创建连接到树的每个子节点的混合类别...

标签: mysql laravel laravel-5 eloquent


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2019-01-23
  • 2021-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
相关资源
最近更新 更多