Laravel可选WHERE子句

时间:2017-10-20 14:30:20

标签: php mysql laravel laravel-5.3

有没有办法在Laravel中实现可选的WHERE,这是我的查询

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

在这里,我希望这一行是可选的

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

因此,如果搜索不包含时间,它将完全忽略此行查询。

whereDate是必需的,但不需要whereTime。如果获得时间请求,它将查询时间,但如果未获得时间请求,则将忽略whereTime查询,并仅显示whereDate的结果。

我怎样才能在Laravel中实现这一目标?

3 个答案:

答案 0 :(得分:9)

根据https://laravel.com/docs/5.3/queries#conditional-clauses

->when($request->get('time'), function($query) use ($request) {
     $query->whereTime('datetime', '=', $request->get('time')); 
})

答案 1 :(得分:3)

简单的事情是:

$peopleQuery = \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'));
        if ($request->has("time")) {
            $peopleQuery->whereTime ('datetime', '=', $request->get('time'));
        }
        $people = $peopleQuery->get();

答案 2 :(得分:1)

您可以使用'when'方法。请在此处阅读:https://laravel.com/docs/5.5/queries#conditional-clauses

$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'))
            -> when($request->get('time'), function($query) use($request) { 
                 $query->where('datetime', '=', $request->get('time')
             })-> get();