私は Laravel Eloquent クエリ ビルダーを使用していますが、複数の条件に句が必要なクエリがありますWHERE
。 動作しますが、エレガントではありません。
例:
$results = User::where('this', '=', 1)
->where('that', '=', 1)
->where('this_too', '=', 1)
->where('that_too', '=', 1)
->where('this_as_well', '=', 1)
->where('that_as_well', '=', 1)
->where('this_one_too', '=', 1)
->where('that_one_too', '=', 1)
->where('this_one_as_well', '=', 1)
->where('that_one_as_well', '=', 1)
->get();
これを行うにはもっと良い方法がありますか、それともこの方法に固執するべきでしょうか?
ベストアンサー1
でララベル5.3(そして今もそうだ7.x) 配列として渡されるより細かい where を使用できます。
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
個人的には、複数の呼び出しでこれを使用するケースは見つかりませんでしたwhere
が、実際には使用できます。
2014年6月以降、配列を渡すことができるようになりましたwhere
wheres
すべてのuse演算子が必要な場合はand
、次のようにグループ化できます。
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];
// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
それから:
$results = User::where($matchThese)->get();
// with another group
$results = User::where($matchThese)
->orWhere($orThose)
->get();
上記のクエリの結果は次のようになります:
SELECT * FROM users
WHERE (field = value AND another_field = another_value AND ...)
OR (yet_another_field = yet_another_value AND ...)