Laravel:在 JOIN with Fluent 中使用复杂条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16082214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:42:58  来源:igfitidea点击:

Laravel: Use complex condition in JOIN with Fluent

laravellaravel-3

提问by jmadsen

For reasons of a complex schema & a library that requires either Fluent or Eloquent to be used (not just raw DB::query() ), I need to create:

由于复杂的模式和需要使用 Fluent 或 Eloquent 的库(不仅仅是原始 DB::query() ),我需要创建:

LEFT JOIN `camp_to_cabin` 
ON `camper_to_cabin`.`cabin_id` = `camp_to_cabin`.`cabin_id`
AND `camp_to_cabin`.`camp_id` =1 OR `camp_to_cabin`.`camp_id` IS NULL

as the join clause; I've tried the callbacks & everything else I can think of, but cannot get the proper syntax to generate.

作为连接子句;我已经尝试了回调和我能想到的所有其他内容,但无法获得正确的语法来生成。

I have tried:

我试过了:

    ->left_join('camp_to_cabin', function ($join){
        $join->on( 'camper_to_cabin.cabin_id', '=', 'camp_to_cabin.cabin_id')
        $join->on( 'camp_to_cabin.camp_id', '=', 1)
        $join->on( 'camp_to_cabin.camp_id', '=', null)

    })

but it puts backticks around my 1 & null (I know the null bit isn't right - experimenting) that I can't get rid of; otherwise it looks pretty close

但它在我的 1 & null 周围加上了反引号(我知道 null 位不正确 - 正在试验)我无法摆脱;否则它看起来很接近

Any help?

有什么帮助吗?

TIA

TIA



Thanks, Phil - final answer is:

谢谢,菲尔 - 最终答案是:

->left_join('camp_to_cabin', function ($join) use ($id){
$join->on( 'camper_to_cabin.cabin_id', '=', 'camp_to_cabin.cabin_id');
$join->on( 'camper_to_cabin.cabin_id', '=', DB::raw($id));
$join->or_on( 'camper_to_cabin.cabin_id', 'IS', DB::raw('NULL'));
 })

回答by Phill Sparks

Looks like you need to use DB::raw()otherwise ->on()expects two columns. Something like...

看起来你需要使用DB::raw()否则->on()需要两列。就像是...

->left_join('camp_to_cabin', function ($join){
    $join->on( 'camper_to_cabin.cabin_id', '=', 'camp_to_cabin.cabin_id')
    $join->on( 'camp_to_cabin.camp_id', '=', DB::raw(1))
    $join->or_on( 'camp_to_cabin.camp_id', '=', DB::raw(null))
})