Laravel多条件外部左连接与外部变量

时间:2020-04-17 08:49:13

标签: mysql laravel left-join outer-join

早上好,我有以下多次加入。我想要它作为外部。它对我不起作用...因为它将外部联接更改为内部联接。

$query=DB::Table("Users")->select("Users.*","Strings.Text as Title","Strings2.Text as Name" ,"Strings3.Text as Description", "Strings4.Text as Summary")
    ->join("Strings",function($join) use($bbddlang)
        {
            $join->on("Users.HeroTitle","Strings.StringID");
            $join->where("Strings.Lang",$bbddlang);
        }, "left outer")
    ->join("Strings as Strings2",function($join) use($bbddlang)
        {
            $join->on("Users.HeroName","Strings2.StringID");
            $join->where("Strings2.Lang",$bbddlang);
        }, "left outer")
    ->join("Strings as Strings3",function($join) use($bbddlang)
        {
            $join->on("Users.Description","Strings3.StringID");
            $join->where("Strings3.Lang",$bbddlang);
        }, "left outer")
    ->join("Strings as Strings4",function($join) use($bbddlang)
        {
            $join->on("Users.Summary","Strings4.StringID");
            $join->where("Strings4.Lang",$bbddlang);
        }, "left outer")
    ->where("Strings.Text",$hero);

这是我使用ToSql()方法得到的:

select `Users`.*, `Strings`.`Text` as `Title`, `Strings2`.`Text` as `Name`, `Strings3`.`Text` as `Description`, `Strings4`.`Text` as `Summary` 
from `Users` 
inner join `Strings` 
    on `Users`.`HeroTitle` = `Strings`.`StringID` 
    and `Strings`.`Lang` = ? 
inner join `Strings` as `Strings2` 
    on `Users`.`HeroName` = `Strings2`.`StringID` 
    and `Strings2`.`Lang` = ? 
inner join `Strings` as `Strings3` 
  on `Users`.`Description` = `Strings3`.`StringID` 
      and `Strings3`.`Lang` = ? 
inner join `Strings` as `Strings4` 
  on `Users`.`Summary` = `Strings4`.`StringID` 
      and `Strings4`.`Lang` = ? 
where `Strings`.`Text` = ?

(?是查询的外部变量,那不是问题)。

在一个条件下,就像这样

->join('answers as answers', 'responses.answer_id', '=', 'answers.id', 'left outer')

我尝试过使用leftjoin,它将内部联接替换为左联接,但是将参数传递给外部也没有用...因为外部没有出现在查询中。

我的问题是为什么它忽略传递的“外部联接”参数?当第二个连接参数是一个函数时,我会错过另一个参数吗?

1 个答案:

答案 0 :(得分:0)

选中join-function-source-code

join(字符串$ table,字符串$ first,字符串| null $ operator = null,字符串| null $ second = null,字符串$ type ='inner',bool $ where = false)

$first可以是Closure的实例,因此,当您使用Closure作为第二个参数,"left join"作为$operator的第三个参数时,$type的默认值为{{ 1}}。这就是为什么原始sql总是返回"inner"的原因。

您需要将inner join ...置于第五位置:

LEFT OUTER

因此,建议使用->join("Strings", function($join) use($bbddlang) { $join->on("Users.HeroTitle","Strings.StringID"); $join->where("Strings.Lang",$bbddlang); }, null, null, "left outer") 而不是leftjoin来关闭

join