使用多个选项过滤php mysql



我有一个度假旅行数据库,并希望同时按3个参数(目的地,出发日期,酒店国家(。

所以我以HTML表单(目的地,日期,酒店(创建了三个输入

<form action="/search-tours" method="GET">
<input name="destination" type="text">
<input name="date" type="date">
<input name="hotel" type="text">
<button type=submit>Search tours</button>

我正在使用Laravel,因此我的PHP代码位于控制器中(" Tour"是DB中与表" Tours"的模型=连接(。

        $destination = $request->get('destination');
        $date = $request->get('date');
        $hotel = $request->get('hotel');

        $tours = Tour::where('destination', '=', $destination)
                      ->where('departure', '=' , $date)
                      ->where('hotel', '=', $hotel)
                     ->get();

当我提交所有输入时,它给出了正确的结果,但是当缺少任何输入时,它根本不起作用。

我认为我可以通过IF-ELSE解决它,但是我意识到可以存在7种情况(1-参数存在,0-丢失:对于EX目的地(1(-date(0(-Hotel(0(= 100,总计:111、100、010、001、110、011、101-我们不在乎000(。如果我们有4个输入,那将是15、5参数-31等。

所以写这么多的if-else是很乏味的,那么这意味着还有另一个。

如果只给出1或2个输入,我应该采用哪种方法来工作?

$query = (new Tour)->newQuery();
if($request->has('destination')){
    $query->where('destination', '=', $request->get('destination'));
}
if($request->has('date')){
    $query->where('departure', '=', $request->get('date'));
}
if($request->has('hotel')){
    $query->where('hotel', '=', $request->get('hotel'));
}
$tours = $query->get();

最新更新