You need to enable JavaScript to run this app. Laravel Eloquent中使用orWhere查询满足指定关联条件的Courrier数据
优惠活动
大模型
产品
解决方案
定价
更多

Laravel Eloquent中使用orWhere查询满足指定关联条件的Courrier数据

解决方案

问题原因

你原有写法的逻辑会被解析为 (courriers.repondre = 1 AND 无关联reponses) OR reponses.structure <> 'DMO',OR 条件会直接跳过repondre=1的限制,不符合你要求的两个场景都必须满足repondre=1的规则。另外直接在orWhere中写关联表字段reponses.structure会触发字段不存在的错误,且你需求中要过滤的是INFO不是代码里写的DMO,属于笔误。

正确实现代码

$courriers = Courrier::where('repondre', 1)
    ->where(function ($query) {
        // 条件1:没有关联的reponses
        $query->doesntHave('reponses')
              // 条件2:不存在structure为INFO的关联reponses
              ->orWhereDoesntHave('reponses', function ($subQuery) {
                  $subQuery->where('structure', 'INFO');
              });
    })
    ->get();

逻辑说明

  • 外层的where('repondre', 1)是全局强制条件,所有返回结果都必须满足,不会被内部OR逻辑影响
  • 内层闭包将两个可选条件打包,满足任意一个即可命中:
    • doesntHave('reponses') 对应需求的第一种场景:该courrier没有关联的reponses记录
    • orWhereDoesntHave 对应需求的第二种场景:不存在任何structure='INFO'的关联reponses,也就是所有关联的reponses的structure都不等于'INFO'

内容的提问来源于stack exchange,提问作者MERAH Samia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 02:06:00