You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中含OR与AND的WHERE子句MySQL查询报错求助

Laravel 多条件查询修正方案

你写的查询逻辑存在优先级问题,orWhere会打乱条件组合逻辑,最终生成的SQL并非你预期的「categories_id为31/211/18 且 status和mode都为on」,而是变成了「满足categories_id=31,或categories_id=211,或(categories_id=18且status、mode为on)」,不符合需求。

以下是两种正确的实现方式:

方案一:使用whereIn简化多值匹配

$subcategories = DB::table('subcategories')
    ->whereIn('categories_id', [31, 211, 18])
    ->where('status', 'on')
    ->where('mode', 'on')
    ->get();

whereIn会将categories_id的条件整合成categories_id IN (31,211,18),和后续两个where条件保持AND关系,完全匹配需求。

方案二:用闭包分组OR条件(适配复杂场景)

$subcategories = DB::table('subcategories')
    ->where(function($query) {
        $query->where('categories_id', 31)
              ->orWhere('categories_id', 211)
              ->orWhere('categories_id', 18);
    })
    ->where('status', 'on')
    ->where('mode', 'on')
    ->get();

闭包会将内部的OR条件用括号包裹,生成的SQL为(categories_id=31 OR categories_id=211 OR categories_id=18) AND status='on' AND mode='on',确保逻辑优先级正确。

内容的提问来源于stack exchange,提问作者Aashish Kumar Jaiswal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 05:35:18