Laravel查询构建器能否单表左关联双外键并设置优先级?
解决方案:单次左关联实现双外键优先级匹配
你可以利用SQL的coalesce()函数在关联条件中指定优先级,只需要一次左关联就能实现需求:
DB::connection('...')->table('some_table') ->leftJoin('table_that_should_take_presedence as ttstp', 'ttstp.id', '=', 'some_table.ttstp_id') ->leftJoin('some_other_table as sot', function ($join) { $join->on('sot.id', '=', DB::raw('coalesce(ttstp.some_other_table_id, some_table.some_other_table_id)')); }) ->select('sot.example') // 直接取关联表字段即可,无需合并多个别名 ->get();
逻辑说明
coalesce(ttstp.some_other_table_id, some_table.some_other_table_id)会优先返回ttstp.some_other_table_id的非空值,当该字段为空时,自动使用some_table.some_other_table_id的值进行关联- 仅需一次关联
some_other_table,避免了重复关联带来的冗余,查询逻辑更简洁高效
内容的提问来源于stack exchange,提问作者Jaquarh
相关产品推荐
相关产品推荐

