在Laravel中过滤多个DB列的好方法

时间:2014-03-17 01:59:37

标签: php sql laravel

我想在多个 DB 列中再次过滤我的结果,但我现在正在做的方式似乎根本不是Laravel-ish :)

有更好的方法吗?我不想在最后堆积所有sql语句。

$data = Input::except('_token');

        if (isset($data['passenger_name']))
        {
            $passenger_name = $data['passenger_name'];
        } else {
            $passenger_name = '*';
        }

        if (isset($data['passenger_lastname']))
        {
            $passenger_lastname = $data['passenger_lastname'];
        } else {
            $passenger_lastname = '*';
        }

        // Run query
        $q = Reservation::where('passenger_firstname', 'LIKE', '%'. $passenger_name .'%')
                        ->where('passenger_lastname', 'LIKE', '%' . $passenger_lastname .'%')
                        ->get();

        return View::make('dashboard')->with('reservations', $q);


这些只是我必须针对

运行查询的众多标准中的两个

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

$query = Reservation::query();
if(Input::has('passenger_name')) {
    $query->where('passenger_name', Input::get('passenger_name'));
}
if(Input::has('passenger_lastname')) {
    $query->where('passenger_lastname', Input::get('passenger_lastname'));
}
$reservations = $query->get();
return View::make('dashboard')->with('reservations', $reservations);