14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel の leftJoin で、クロージャを使えば複数条件指定もできる

Posted at

突然ですが、こんな感じの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つ目の年齢の条件が指定できない・・・

と、困りながらマニュアルをちゃんと読んでみたら、なんと第二引数にはクロージャも指定できるらしい :eyes:

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;
    }

14
15
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?