如何使这个查询更简单,更容易?

时间:2017-05-11 09:43:44

标签: php mysql laravel

在这个Laravel查询中,任何人都可以搜索这些字段,但问题是当某人没有选择所有可搜索的字段时会产生错误。因为whereIn方法没有获得变量的值。如果我使用if条件进行检查,那么它将是一个非常大的sql。那么,有没有简单的方法可以轻松地做到这一点。我的查询如下。谢谢您的帮助。

public function filter(Request $r){
    searchQuery = DB::table('jobs')->whereIn('division_id', $r->location)->whereIn('industrytype_id', $r->industry)->whereIn('category_id', $r->category)->whereIn('company_id', $r->company_id)->whereIn('created_at', $r->date)->whereIn('salary_range', $r->salary_range)->whereIn('jobType', $r->jobType)->orderByRaw($r->shortby)->get();
}  

3 个答案:

答案 0 :(得分:0)

WhereIn是一种应该使用数组的方法。你的方法应该是这样的:

public function filter(Request $r){  
    $searchQuery=DB::table('jobs')->where('division_id',$r->location)->where('industrytype_id',$r->industry)->where('category_id',$r->category)->where('company_id',$r->company_id)->where('created_at',$r->date)->where('salary_range',$r->salary_range)->where('jobType',$r->jobType)->orderBy($r->shortby)->get(); 
} 

答案 1 :(得分:0)

我认为你只需要接受(SQL)语句就会变大。我想你有这样的事情:?

public function filter(Request $r){
    $searchQuery = DB::table('jobs');

    if($r->location){
        $searchQuery->whereIn('division_id', $r->location);
    }
    if($r->industry){
        $searchQuery->whereIn('industrytype_id', $r->industry);
    }
    if($r->category){
        $searchQuery->whereIn('category_id', $r->category);
    }
    if($r->company_id){
        $searchQuery->whereIn('company_id', $r->company_id);
    }
    if($r->date){
        $searchQuery->whereIn('created_at', $r->date);
    }
    if($r->salary_range){
        $searchQuery->whereIn('salary_range', $r->salary_range);
    }
    if($r->jobType){
        $searchQuery->whereIn('jobType', $r->jobType);
    }

    $searchQuery->orderByRaw($r->shortby)->get();
}

如果你经常这样做,你可以编写自己的DB类来继承laravel DB类。并在您自己的类中编写一些函数,如$searchQuery->WhereInIfNotNull('industrytype_id', $r->industry);

答案 2 :(得分:0)

我会使用范围将每个过滤器添加到查询中。在您的模型上定义它。快速样品:

 public function scopeDivision($query,$searchParameter)
 {
    if(!is_null($searchParameter){
      return $query->whereIn('division_id', $searchParameter);
    }else{
      return $query;
    }
 }

 public function scopeIndustryType($query,$searchParameter)
 {
    if(!is_null($searchParameter){
      return $query->whereIn('industrytype_id', $searchParameter);
    }else{
      return $query;
    }
 }

然后回到你的过滤器中使用它:

Job::division($r->location)
 ->industryType($r->industry)
 ->category($r->category)
 ->company($r->company_id)
 ->created($r->date)
 ->salaryRange($r->salary_range)
 ->jobType($r->job_type)
 ->orderByRaw($r->shortby)
->get()
相关问题