在laravel中使用leftJoin添加多個條件時,如select a.* from a left join b on a.id = b.pid and b.status = 1這種相似sql,發現框架自身封裝的leftJoin不支持多個參數傳遞(固然可用寫原生sql),laravel框架自身封裝的leftJoin方法以下:php
public function leftJoin($table, $first, $operator = null, $second = null)
{
return $this->join($table, $first, $operator, $second, 'left');
}laravel
瀏覽下 \vendor\laravel\framework\src\Illuminate\Database\Query\Builder.php文件,發現join方法可用實現本身想要的left join攜帶多參數。laravel自身的join方法以下:sql
public function join($table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
{
// If the first "column" of the join is really a Closure instance the developer
// is trying to build a join with a complex "on" clause containing more than
// one condition, so we'll add the join and call a Closure with the query.
if ($one instanceof Closure) {
$join = new JoinClause($type, $table);appcall_user_func($one, $join);框架
$this->joins[] = $join;ui
$this->addBinding($join->bindings, 'join');
}this// If the column is simply a string, we can assume the join simply has a basic
// "on" clause with a single condition. So we will just build the join with
// this simple join clauses attached to it. There is not a join callback.
else {
$join = new JoinClause($type, $table);code$this->joins[] = $join->on(
$one, $operator, $two, 'and', $where
);get$this->addBinding($join->bindings, 'join');
}stringreturn $this;
}
當左右鏈接攜帶多條件時,能夠這樣寫:
DB::table('app_a as a') ->join('app_b as b',function($join){ $join->on('a.id','=','b.goodId') ->where('b.status','=','SUCCESS') ->where('b.type','=','UNLOCK'); }, null,null,'left') ->where('a.id','>',1) ->get(); //至關於 SELECT * FROM app_a as a LEFT JOIN app_b as b on a.id = b.goodId and b.status = 'SUCCESS' and b.type = 'UNLOCK' where a.id > 1;
當join不傳left時,默認是inner。