Laravel可选WHERE子句

Cow*_*irl 3 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();
Run Code Online (Sandbox Code Playgroud)

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

-> whereTime ('datetime', '=', $request->get('time'))
Run Code Online (Sandbox Code Playgroud)

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

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

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

小智 10

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

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


apo*_*fos 7

简单的做法是:

$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();
Run Code Online (Sandbox Code Playgroud)