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

Laravel whereDate()查询搭配orWhere搜索条件时不生效如何解决?

问题根因

你的查询失效的核心原因是SQL逻辑运算符的优先级问题:
原有代码传入搜索参数后,最终拼接的SQL条件等价于:

where fixture_date >= ? and fixture_date <= ? or fixture_hometeam_name like ? or fixture_awayteam_name like ?
SQL中or的优先级低于and,所以只要球队名称匹配搜索词,不管日期是否符合范围,都会被查询出来,表现为日期筛选条件失效。

修复方案

你需要把两个orWhere的搜索条件封装到独立的条件分组中,保证日期筛选是全局必满足的前置条件,修改后代码如下:

->whereDate('fixture_date', '>=', Carbon::now()->subDays($pastDays))
->whereDate('fixture_date', '<=', Carbon::now()->addDays($futureDays))
->when(request('search'), function ($query) {
    // 将搜索条件放入独立分组,限制逻辑优先级
    $query->where(function ($groupQuery) {
        $groupQuery->where('fixture_hometeam_name', 'LIKE', '%' . request('search') . '%')
              ->orWhere('fixture_awayteam_name', 'LIKE', '%' . request('search') . '%');
    });
})

修改后生成的SQL逻辑为:

where (fixture_date >= ? and fixture_date <= ?) and (fixture_hometeam_name like ? or fixture_awayteam_name like ?)
此时会同时满足「日期在指定范围内」和「主/客队名称匹配搜索词」两个要求,查询逻辑符合预期。


内容的提问来源于stack exchange,提问作者Tim Kariuki

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:24:05