2017-08-24 99 views
0

萬一我有過濾器的用戶與地點和日期,我已經寫了查詢像下面過濾器在laravel5.4

public function searchConsultants() 
{ 
    $location = $request->get('location'); 
    $fromDate = $request->get('from_date'); 
    $toDate = $request->get('to_date'); 
    $data = DB::table('consultants') 
    ->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0))as avg_rating, consultants.id,consultants.cunsultant_name,contact_number,location') 
    ->where('location','LIKE','%'.$location.'%') 
    ->whereBetween('date',[$fromDate,$toDate]) 
    ->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id') 
    ->groupBy('consultants.id') 
    ->orderBy('avg_rating', 'DESC') 
    ->get(); 
} 

有了上面的查詢,我可以得到的數據,但有時我不想帶日期搜索我想只搜索位置,

上述查詢中的問題我必須輸入位置和日期來過濾用戶,那麼如何過濾只有位置或日期。

+0

https://stackoverflow.com/a/35926066/5808894 – linktoahref

回答

0

使用orWhere在https://laravel.com/docs/5.4/queries#where-clauses

public function searchConsultants() 
{ 
    $location = $request->get('location'); 
    $fromDate = $request->get('from_date'); 
    $toDate = $request->get('to_date'); 
    $data = DB::table('consultants') 
    ->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0))as avg_rating, consultants.id,consultants.cunsultant_name,contact_number,location') 
    ->where('location','LIKE','%'.$location.'%') 
    ->orwhereBetween('date',[$fromDate,$toDate]) 
    ->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id') 
    ->groupBy('consultants.id') 
    ->orderBy('avg_rating', 'DESC') 
    ->get(); 
} 
0

閱讀它要試試這個:

public function searchConsultants() 
{ 
    $location = $request->get('location'); 
    $fromDate = $request->get('from_date'); 
    $toDate = $request->get('to_date'); 
    $data = DB::table('consultants') 
    ->selectRaw('AVG(COALESCE(ratings.rating_for_manager, 0))as avg_rating, consultants.id,consultants.cunsultant_name,contact_number,location') 
    ->whereBetween('date',[$fromDate,$toDate]) 
    ->orWhere('location','LIKE','%'.$location.'%')  
    ->leftJoin('ratings', 'ratings.consultant_id', 'consultants.id') 
    ->groupBy('consultants.id') 
    ->orderBy('avg_rating', 'DESC') 
    ->get(); 
} 

希望這對你的工作!