donglan9517 2014-03-17 01:59
浏览 54
已采纳

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

I want to filter my results agains multiple DB columns but the way I'm doing it right now doesn't seem Laravel-ish at all :)

Is there a better way? I don't want to pile up all those sql statements at the end.

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


These are just two of many criteria i have to run queries against

  • 写回答

1条回答 默认 最新

  • dqd3690 2014-03-17 02:27
    关注

    You may try this:

    $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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀