突然ですが、こんな感じのSQLを書きたくなることありませんか?
-- 家族の情報を全て取得、5歳以下の子供がいればその情報も一緒に
SELECT * FROM families
INNER JOIN persons
ON families.id = persons.family_id
AND persons.age <= 5;
Laravel の join
leftJoin
メソッドだと、こんな感じで
Family::leftJoin('persons', 'families.id', '=', 'persons.family_id')->get();
第二引数〜第四引数に ON 句の条件が入るから、2つ目の年齢の条件が指定できない・・・
と、困りながらマニュアルをちゃんと読んでみたら、なんと第二引数にはクロージャも指定できるらしい
Family::leftJoin('persons', function ($join) {
$join->on('families.id', '=', 'persons.family_id')
->where('persons.age', '<=', 5)
})->get();
これでOK!
join
の機能なので、 leftJoin
限定でなく色々使えそうです。
join のコードはこうなってた。
public function join($table, $first, $operator = null, $second = null, $type = 'inner', $where = false)
{
$join = $this->newJoinClause($this, $type, $table);
if ($first instanceof Closure) {
$first($join);
$this->joins[] = $join;
$this->addBinding($join->getBindings(), 'join');
}
else {
$method = $where ? 'where' : 'on';
$this->joins[] = $join->$method($first, $operator, $second);
$this->addBinding($join->getBindings(), 'join');
}
return $this;
}