我用搜索参数调用URL是动态的.我怎么能形成适当的Eloquent查询?
理论上:
我需要这种结构,所以如果param存在,我可以使用where子句.如果Laravel有其他方式,请告诉我.
Bak*_*ems 67
Laravel很容易.做这样的事情:
$query = User::query();
if ($this == $that) {
$query = $query->where('this', 'that');
}
if ($this == $another_thing) {
$query = $query->where('this', 'another_thing');
}
if ($this == $yet_another_thing) {
$query = $query->orderBy('this');
}
$results = $query->get();
Run Code Online (Sandbox Code Playgroud)
您可以只使用 where 语句。例如:在users表或User模型上,您需要对名称、ID 进行动态搜索。你可以这样做
$where = [];
$firstName = $request->get('first_name');
if ($firstName) $where[] = ['first_name', 'like'. '%' . $firstName . '%'];
$id = $request->get('id');
if ($id) $where[] = ['id', $id];
$users = User::where($where)->get();
Run Code Online (Sandbox Code Playgroud)
默认情况下,它将返回所有用户,如果$where数组中存在任何内容,它将对其应用where condition。
| 归档时间: |
|
| 查看次数: |
17045 次 |
| 最近记录: |