--- tags: Laravel, left join, db --- # Laravel left join攜帶多個條件的寫法 laravel框架自身封裝的leftJoin方法如下: ```php= public function leftJoin($table, $first, $operator = null, $second = null) { return $this->join($table, $first, $operator, $second, ‘left’); } ``` 瀏覽下 \\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php檔案,發現join方法可用實現自己想要的left join攜帶多引數。laravel自身的join方法如下: ```php= 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); call_user_func($one, $join); $this->joins[] = $join; $this->addBinding($join->bindings, ‘join’); } // 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); $this->joins[] = $join->on( $one, $operator, $two, ‘and’, $where ); $this->addBinding($join->bindings, ‘join’); } return $this; } ``` 當攜帶多條件時,可以這樣寫: ```php= ->leftJoin('cert_group as cg',function($join){ $join->on('cg.id', '=', 'cgm.cg_id') ->on('cg.cp_id', '=', 'cgm.cp_id'); }) ``` 或 ```php= ->join('app_b as b',function($join){ $join->on('a.id','=','b.goodId') ->where('b.status','=','SUCCESS') ->where('b.type','=','UNLOCK'); }, null,null,'left') ```