我使用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();
有没有更好的方法,或者我应该坚持这个方法?
你可以在几种情况下使用,
$results = User::where([
['column_name1', '=', $value1],
['column_name2', '<', $value2],
['column_name3', '>', $value3]
])->get();
你也可以这样用,
$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<', $value2);
$results = $results->where('column3','>', $value3);
$results = $results->get();
在Eloquent中,你可以这样做:
$results = User::where('this', '=', 1)
->orWhere('that', '=', 1)
->orWhere('this_too', '=', 1)
->orWhere('that_too', '=', 1)
->orWhere('this_as_well', '=', 1)
->orWhere('that_as_well', '=', 1)
->orWhere('this_one_too', '=', 1)
->orWhere('that_one_too', '=', 1)
->orWhere('this_one_as_well', '=', 1)
->orWhere('that_one_as_well', '=', 1)
->get();
你可以在几种情况下使用,
$results = User::where([
['column_name1', '=', $value1],
['column_name2', '<', $value2],
['column_name3', '>', $value3]
])->get();
你也可以这样用,
$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<', $value2);
$results = $results->where('column3','>', $value3);
$results = $results->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();