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和子查询,代码可读性和可维护性更高:
- 先在
DspAccount模型定义和Dsp的一对多关联 - 在
Dsp模型定义和rtbcfg_region_dsp对应模型的一对多关联 - 用如下代码查询即可:
$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
相关产品推荐
相关产品推荐

