2017-10-20 163 views
2

有沒有辦法實現的可選凡在Laravel,這是我的查詢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中實現此目標?

+0

你可以把它分解成過濾HTTP:// laraveltnt。 com/conditional-eloquent-clause/ – prola

回答

0

您可以使用'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(); 
+0

這可能是正確的方法,但你應該提供一個例子 – apokryfos

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