在laravel5.4中过滤

问题描述 投票:0回答:2

如果我有过滤用户的位置和日期,我写了如下的查询

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

通过上面的查询我可以得到数据,但有时我不想搜索日期我只想搜索位置,

上述查询中的问题我必须输入位置和日期来过滤用户,那么如何只使用位置或日期进行过滤。

laravel laravel-5 laravel-5.4
2个回答
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();
}
© www.soinside.com 2019 - 2024. All rights reserved.