dongqing483174 2017-10-20 14:30
浏览 509
已采纳

Laravel可选WHERE子句

Is there a way to achieve an optional WHERE in Laravel, this is my query

$people = \App\people::query()
        -> select ('people.name', 'people.username', 'price', 'service','people.city', 'people.streetaddress', 'people.postalcode', DB::raw("GROUP_CONCAT(DATE_FORMAT(datetime, '%H:%i')) as times"))
        -> groupBy('people') 
        -> leftjoin ('services' , 'people.id', '=', 'services.people_id')
        -> leftjoin ('imagesforpeople' , 'people.id', '=', 'imagesforpeople.people_id')
        -> whereDate ('datetime', '=', $request->get('date'))
        -> whereTime ('datetime', '=', $request->get('time'))
        -> get();

Here, I want this line to be optional

-> whereTime ('datetime', '=', $request->get('time'))

So, if the search does not contain a time, it will completely ignore this line of query.

whereDate is required, but whereTime is not required. If the time request is obtained, it will query for time, but if the time request is not obtained it will ignore the whereTime query, and will show result for whereDate only.

How can I achieve this in Laravel?

  • 写回答

3条回答 默认 最新

  • douyi6922 2017-10-20 14:37
    关注

    As per https://laravel.com/docs/5.3/queries#conditional-clauses

    ->when($request->get('time'), function($query) use ($request) {
         $query->whereTime('datetime', '=', $request->get('time')); 
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?