我正在为构建RESTAPI开发一个Laravel项目。我正在使用eloquent从数据库中Fatch数据。如果只有一个WHERE和一个WHERE条件,它没有问题,但在这里我使用多个WHERE子句。比如,如果我们编写核心MySQL查询,我们可以这样写:
SELECT * FROM table_name WHERE uid = 1
AND (id = 1 AND name = test1) OR (id = 2 AND name = test2);
但是当我们使用eloquent,以及在模型中使用 orWhere 时,我们需要这样做:
Model::select('*')->where('uid', '1')
->where('id', '1')
->where('name', 'test1')
->orWhere('uid', '1')
->where('id', '1')
->where('name', 'test1')
->get();
有时,当我尝试制作任何可以根据表的参数数搜索数据的搜索API时,我需要多次编写相同的代码。
The equivalent in eloquent
of parenthesis would be using a closure as the parameter of where
or orWhere
(a or b) and (c or d)
would be:
->where(function($q){
$q->where(a)->orWhere(b);
})->where(function($q){
$q->where(c)->orWhere(d);
});
and
(a and b) or (c and d)
would be:
->where(function($q){
$q->where(a)->where(b);
})->orWhere(function($q){
$q->where(c)->where(d);
});
but
a or b and c or d
would be:
->where(a)->orWhere(b)->where(c)->orWhere(d)
which is something completely different.
Use where() or orWhere()
closure for parameter grouping
Model::select('*')->where('uid', '1')->where(function($q){
$q->where('id', '1')->where('name', 'test1')
})->orWhere(function($q){
$q->where('id', '1')->where('name', 'test1')
})->get();
From Docs
Passing a
Closure
into theorWhere
method instructs the query builder to begin a constraint group. The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group.
This code will be helpfull for you
Model::where([['uid', '1'],['id', '1'],['name', 'test1']])
->orWhere([['uid', '1'],['id', '1'],['name', 'test1']])
->get();