首页 > 解决方案 > 如何使用多个表单输入查询搜索

问题描述

我有一个具有多个输入字段的搜索函数,只要其中一个输入为空,它就会返回错误。

我已经尝试过这段代码,但它只是返回查询语句,而不是结果本身

  $employees = DB::table('job_requests')
            ->select('job_requests.*','user_infos.*')
            ->leftJoin('user_infos','user_infos.user_id','=','job_requests.user_id')
            ->where('user_infos.role','=','0');

  if ($job_name) {
     $employees->where('job_requests.job_name','like',"%$job_name%");
  }
  if ($location) {
     $employees->where('job_requests.location','=',$location);
  }
  if ($gender) {
     $employees->where('user_infos.gender','=',$gender);
  }
  if ($salary) {
     $employees->where('job_requests.salary','<=',$salary);
  }
  if ($start_date && $end_date) {
     $employees->whereBetween('end_date',array($start_date,$end_date));
  }
  $employees->get();

我希望输出是查询的结果

标签: laravel

解决方案


我认为您应该使用此代码

$employees = DB::table('job_requests')
            ->select('job_requests.*','user_infos.*')
            ->leftJoin('user_infos','user_infos.user_id','=','job_requests.user_id')
            ->where('user_infos.role','=','0');

  if (isset($job_name) && !empty($job_name)) {
     $employees->andWhere('job_requests.job_name','like',"%$job_name%");
  }
  if (isset($location) && !empty($location)) {
     $employees->andWhere('job_requests.location','=',$location);
  }
  if (isset($gender) && !empty($gender)) {
     $employees->andWhere('user_infos.gender','=',$gender);
  }
  if (isset($salary) && !empty($salary)) {
     $employees->andWhere('job_requests.salary','<=',$salary);
  }
  if (isset($start_date) && !empty($start_date) && isset($end_date) && !empty($end_date)) {
     $employees->whereBetween('end_date',array($start_date,$end_date));
  }
  $employees->get();

希望这能解决您的问题。


推荐阅读