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

如何将给定多表关联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相关报错,可通过两种方式解决:

  1. 打开config/database.php,找到mysql配置项,将strict参数设置为false
  2. 在groupBy前新增select方法,显式指定所有你需要查询的company表字段,例如->select('c.id', 'c.name', 'c.owner_user_id')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:36:05