我使用Laravel雄辩的查询构建器,我有一个查询,我想在多个条件上有一个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();
有没有更好的方法,或者我应该坚持这个方法?
Model::where('column_1','=','value_1')
->where('column_2 ','=','value_2')
->get();
OR
// If you are looking for equal value then no need to add =
Model::where('column_1','value_1')
->where('column_2','value_2')
->get();
OR
Model::where(['column_1' => 'value_1',
'column_2' => 'value_2'])->get();
代码示例。
首先:
$matchesLcl=[];
数组在这里被填充使用所需的计数/循环条件,增量:
$matchesLcl['pos']= $request->pos;
$matchesLcl['operation']= $operation;
//+......+
$matchesLcl['somethingN']= $valueN;
更进一步,他又用了这样一种简洁的表达:
if (!empty($matchesLcl))
$setLcl= MyModel::select(['a', 'b', 'c', 'd'])
->where($matchesLcl)
->whereBetween('updated_at', array($newStartDate . ' 00:00:00', $newEndDate . ' 23:59:59'));
else
$setLcl= MyModel::select(['a', 'b', 'c', 'd'])
->whereBetween('updated_at', array($newStartDate . ' 00:00:00', $newEndDate . ' 23:59:59'));
在Laravel 5.3中(在7.x中仍然如此),你可以使用更细粒度的数组:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
就我个人而言,我还没有发现这个用例超过多个where调用,但事实是你可以使用它。
自2014年6月起,您可以将数组传递到where
只要你想要所有的where use和operator,你可以这样分组:
$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 ...)