LoginSignup
2
1

More than 3 years have passed since last update.

【Laravel】複数のクエリのwhere句を結合する

Last updated at Posted at 2020-06-12

where句をマージする関数は、クエリビルダに存在する

自作しようかと思ったがあった。

/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
    /**
     * Merge an array of where clauses and bindings.
     *
     * @param  array  $wheres
     * @param  array  $bindings
     * @return void
     */
    public function mergeWheres($wheres, $bindings)
    {
        $this->wheres = array_merge($this->wheres, (array) $wheres);

        $this->bindings['where'] = array_values(
            array_merge($this->bindings['where'], (array) $bindings)
        );
    }

追加したいwhere句のwheresとbindingsを渡せば、マージしてくれるらしい

wheresを取得する方法

$query = app('App\Hogehoge');
$wheres = $query->getQuery()->wheres;

bindingsを取得する方法

$query = app('App\Hogehoge');
$bindings = $query->getBindings();

複数のクエリのwhere句を結合する

// もとになるクエリ
$query = app('App\Hogehoge')::join('piyopiyo', 'piyopiyo.id', '=', 'hogehoge.piyopiyo_id')
    ->where('hogehoge.class', 'A');

// 結合したいクエリ
$add_query = app('App\Piyopiyo')
    ->where('piyopiyo.class', 'B');

// queryにadd_queryのwhere句を結合する
$query->getQuery()->mergeWheres(
    $add_query->getQuery()->wheres,
    $add_query->getBindings()
);
2
1
0

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
2
1