mysql - 如果 Laravel 中的某些字段是可选的,则使用下拉菜单过滤数据
问题描述
当用户有 10 个下拉选择框来过滤数据时,我正在做一个项目。问题是用户可能不会使用所有的选择框。所以我想在这一部分中包含一些 if 条件。
public function PostSearch()
{
$eye_color = Input::get('eye_color');
$tattoos = Input::get('tattoos');
$piercings = Input::get('piercings');
....
$user = User::where([['eye_color',$eye_color],
['tattoos',$tattoos],
['piercings',$piercings]])->get();
return $user;
}
如何在查询中使用 if 条件进行输入选择。
解决方案
你可以这样做:
$filters = [
'eye_color' => Input::get('eye_color'),
'tattoos' => Input::get('tattoos'),
'piercings' => Input::get('piercings'),
];
$user = User::where(function ($query) use ($filters) {
if ($filters['eye_color']) {
$query->where('eye_color', '=', $filters['eye_color']);
}
if ($filters['tattoos']) {
$query->where('tattoos', '=', $filters['tattoos']);
}
if ($filters['piercings']) {
$query->where('piercings', '=', $filters['piercings']);
}
})->get();
return $user;
让我知道它是否有效。
推荐阅读
- c++ - C++ 代码不计算时间差,但它返回 -0
- webstorm - 在 WebStorm 中外部更改 CSS 文件后运行“从磁盘重新加载”
- flutter - 如何在颤振中编写模拟赌博应用跟踪器的方法/函数?
- python - 如何显示 Softmax 最高概率
- uwsgi - uWSGI 独立模式下的 http-to 是什么意思
- gstreamer - 如何在视频输出中保存 RTCP 时间信息
- python - 如何将一列添加到聚合的 Pandas 数据框中?
- reactjs - React Ag Grid 与材质主题类
- php - 如何在 WooCommerce 函数中使用带有条件逻辑的 php 标签
- android - Android PhotoEditorView 添加新框架