如何将给定多表关联SQL查询转换为Laravel框架查询构造器代码?
原有代码问题
- 重复关联
merchantlink表两次,会产生错误的笛卡尔积,导致数据结果异常 - 未对OR条件做逻辑分组,查询条件优先级和原生SQL不一致,返回结果不符合预期
- 缺失
merchantlinkrelation.ptype = 'dealer'的全局过滤条件 - 缺失
GROUP BY c.id的去重逻辑
正确转换后的Laravel查询代码
$twowaycompany = DB::table('company as c') ->join('merchantlink as m', function ($join) { $join->on('m.initiator_user_id', '=', 'c.owner_user_id') ->orOn('m.responder_user_id', '=', 'c.owner_user_id'); }) ->join('merchantlinkrelation as mlr', 'mlr.merchantlink_id', '=', 'm.id') ->where('mlr.ptype', 'dealer') ->where(function ($query) { $targetUserId = 86; $query->where(function ($subQ) use ($targetUserId) { $subQ->where('m.initiator_user_id', DB::raw('c.owner_user_id')) ->where('m.responder_user_id', $targetUserId); }) ->orWhere(function ($subQ) use ($targetUserId) { $subQ->where('m.initiator_user_id', $targetUserId) ->where('m.responder_user_id', DB::raw('c.owner_user_id')); }) ->orWhere(function ($subQ) use ($targetUserId) { $subQ->where('m.initiator_user_id', DB::raw('c.owner_user_id')) ->where('c.owner_user_id', $targetUserId); }); }) ->groupBy('c.id') ->pluck('c.name') ->toArray();
注意事项
如果你的项目开启了MySQL严格模式,直接按上述写法执行会触发groupby相关报错,可通过两种方式解决:
- 打开
config/database.php,找到mysql配置项,将strict参数设置为false - 在
groupBy前新增select方法,显式指定所有你需要查询的company表字段,例如->select('c.id', 'c.name', 'c.owner_user_id')
内容的提问来源于stack exchange,提问作者Hamza Qureshi
相关产品推荐
相关产品推荐

