簡體   English   中英

如果Laravel中某些字段是可選的,則使用下拉列表過濾數據

[英]Filter data using Dropdowns if some fields are optional in Laravel

當用戶有10個下拉列表選擇框來過濾數據時,我正在做一個項目。 問題在於用戶可能不會使用所有選擇框。 因此,我想在這一部分中包含一些條件。

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;

讓我知道它是否有效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM