$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();
是否有比这更好的实现方式吗?
在 Laravel 5.3
你可以传递一个 wheres 数组:
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
自2014年6月起,你可以将数组传递给 where
,
只要你想要所有 wheres
使用 and
运算符,你就可以用这种方式对它们进行分组:
$matchThese = ['field' => 'value', 'another_field' => 'another_value', ...];
$orThose = ['yet_another_field' => 'yet_another_value', ...];
$results = User::where($matchThese)->get();
$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 ...)
查询作用域可以帮助你把代码变的更具可读性。
《Laravel 中文文档》
在你的模型中,创建像这样的作用域方法:
public function scopeActive($query)
return $query->where('active', '=', 1);
public function scopeThat($query)
return $query->where('that', '=', 1);
然后,你就可以在构建查询时调用此方法:
$users = User::active()->that()->get();
where
参考:https://stackoverflow.com/questions/1932...
public function testInfo(){
$id=1;
TableOne::whereHas('linkTableTwo',function($query) use ($id){
$query->where('id',$id);
})->with('linkTableTwo')->get();
用了下面的这个,但是效果不太对
User::where(['id' => 1, 'sex' => 0])->orWhere(['id' => 2, 'sex' => 1])->get();
array:1 [▼
0 => array:3 [▼
"query" => "select * from `bl_users` where (`id` = ? and `sex` = ?) or (`id` = ? or `sex` = ?)"
"bindings" => array:4 [▶]
"time" => 3.11
我是想要这样的效果
"select * from `bl_users` where (`id` = ? and `sex` = ?) or (`id` = ? and `sex` = ?)"
这样的怎么可以实现