首页 > 解决方案 > 如果 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 条件进行输入选择。

标签: mysqllaravel

解决方案


你可以这样做:

$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;

让我知道它是否有效。


推荐阅读