我使用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();
如果你的条件是这样的(匹配一个值),一个简单的更优雅的方式是:
$results = User::where([
'this' => value,
'that' => value,
'this_too' => value,
...
])
->get();
但如果你需要OR子句,那么确保你对每个OR where()子句重复必须满足条件。
$player = Player::where([
'name' => $name,
'team_id' => $team_id
])
->orWhere([
['nickname', $nickname],
['team_id', $team_id]
])
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();