Problem
I am in need to have multiple where conditions using the Query builder, in one of my projects for a client. I came up with a solution, just not sure if this is the best way to do it.
Example:
$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();
->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();
Is there a better way to do this, or should I stick with this method?
Solution
As long as you want all the wheres use and operator, you can group them this way:
$matchThese = ['field1' => 'value1', 'field2' => 'value2', ...];
// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
Then:
$results = Organization::where($matchThese)->get();
// with another group
$results = User::where($matchThese)
->orWhere($orThose)
->get();
// if you need another group of wheres as an alternative:
$orThose = ['yet_another_field' => 'yet_another_value', ...];
Then:
$results = Organization::where($matchThese)->get();
// with another group
$results = User::where($matchThese)
->orWhere($orThose)
->get();
The above will result in such query:
SELECT * FROM organizations
WHERE (field1 = value1 AND field2 = value2 AND ...)
OR (yet_another_field = yet_another_value AND ...)
WHERE (field1 = value1 AND field2 = value2 AND ...)
OR (yet_another_field = yet_another_value AND ...)