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

Laravel执行Eloquent多表关联查询报字段不存在错误排查

问题根因

你的代码报错核心是表名/字段引用错误,附带漏写了原SQL的部分逻辑,具体问题点:

  • Eloquent ORM 不会自动将模型类名(比如DspAccount、Dsp)转为表别名注入到SQL中,你代码里写的DspAccount.id、dspAccount.id、DSP.id都是不存在的字段引用,实际三张表的表名就是数据库里定义的蛇形小写:dsp_account、dsp、rtbcfg_region_dsp,没有大小写混合的别名。
  • 你写的Eloquent代码漏了原生SQL里的distinct去重、order by 排序逻辑,和你要实现的需求不完全匹配。
  • 子查询里的having count(*)>0 and status = 1逻辑冗余:status = 1可以直接放到where条件里执行效率更高,count(*) > 0是分组后只要存在记录就满足的默认逻辑,不需要额外写在having中。

异常里自动追加的dsp_account.deleted_at is null是模型开启软删除的正常自动追加条件,不是报错原因。

修正后的可运行代码
$all_list6 = DspAccount::select('dsp_account.id', 'dsp_account.name_display','dsp_account.short_name')
    ->distinct()
    ->join('dsp', 'dsp.dsp_account_id', '=', 'dsp_account.id')
    ->whereIn('dsp.id', function($query)
    {
        $query->select('dsp_id')
            ->from('rtbcfg_region_dsp')
            ->where('status', 1)
            ->groupBy('dsp_id', 'status');
    })
    ->orderBy('dsp_account.name_display', 'ASC')
    ->get();
优化建议

如果已经在三个模型中定义好了关联关系,可以直接用Eloquent关联的whereHas方法实现相同逻辑,不需要手写join和子查询,代码可读性和可维护性更高:

  1. 先在DspAccount模型定义和Dsp的一对多关联
  2. 在Dsp模型定义和rtbcfg_region_dsp对应模型的一对多关联
  3. 用如下代码查询即可:
$all_list6 = DspAccount::select('id', 'name_display', 'short_name')
    ->whereHas('dsp.rtbcfgRegionDsp', function($query) {
        $query->where('status', 1);
    })
    ->distinct()
    ->orderBy('name_display', 'ASC')
    ->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 13:42:29