在 Laravel 的查询构建器中,是否可以将一个表与两个键连接在一起,如果存在一个键,则优先连接?



我试图左加入雄辩查询生成器表,但表有两个潜在的外键。我只想连接一次,但如果潜在的其他列不为空,那么它应该存在。

DB::connection('...')->table('some_table')
->leftJoin('table_that_should_take_presedence as ttstp', 'ttstp.id', '=', 'some_table.ttstp_id')
->leftJoin('some_other_table', function ($otherTable) {
$otherTable->on('some_other_table.id', '=', 'ttstp.some_other_table_id');
//->.... if ttstp.some_other_table_id does not exist then
//       some_table.some_other_table_id should be used
});

到目前为止,我的解决方案是连接表两次,并使用合并来启用该存在:

DB::connection('...')->table('some_table')
->selectRaw('coalesce(sot.example, sot2.example, null) as example')
->leftJoin('table_that_should_take_presedence as ttstp', 'ttstp.id', '=', 'some_table.ttstp_id')
->leftJoin('some_other_table as sot', 'sot.id', '=', 'ttstp.some_other_table_id');
->leftJoin('some_other_table as sot2', 'sot2.id', '=', 'some_table.some_other_table_id');

这似乎不圆滑,我觉得最优的解决方案是加入一次。感谢任何帮助。提前谢谢。

我没理解错,你想要这个:

$q = DB::connection('...')
->table('some_table')
->selectRaw('sot.example')
->leftJoin('table_that_should_take_presedence as ttstp', 'ttstp.id', '=', 'some_table.ttstp_id')
// Try to join by ttstp.some_other_table_id column, if it's null then use some_table.some_other_table_id column
->leftJoin('some_other_table as sot', 'sot.id', '=', DB::raw('COALESCE(ttstp.some_other_table_id, some_table.some_other_table_id)'));
dump($q->toSql());