Laravel5實現模糊比對加多條件查詢功能實現步驟詳解

來源:互聯網
上載者:User
這次給大家帶來Laravel5實現模糊比對加多條件查詢功能實現步驟詳解,Laravel5實現模糊比對加多條件查詢功能實現的注意事項有哪些,下面就是實戰案例,一起來看一下。

方法1. ORM模式

public function ReportAccurate($data){ if(is_array($data)) {   $where = $this->whereAll($data);   return $where; } else {   return false; }}/*多條件模糊*/public function whereAll($data){  $query = new ReportMainpage();  $results = $query->where(function ($query) use ($data) {    $data['report_first_received_date'] && $query->where('report_first_received_date', 'like', '%' . $data['report_first_received_date'] . '%');    $data['report_drug_safety_date'] && $query->where('report_drug_safety_date', 'like', '%' . $data['report_drug_safety_date'] . '%');    $data['aecountry_id'] && $query->where('aecountry_id', $data['aecountry_id']);    $data['received_fromid_id'] && $query->where('received_fromid_id', $data['received_fromid_id']);    $data['research_id'] && $query->where('research_id', 'like', '%' . $data['research_id'] . '%');    $data['center_number'] && $query->where('center_number', 'like', '%' . $data['center_number'] . '%');  })->get();  return $results;}

上面的$data為前端傳過來的數組 利用封裝拼接進行模糊或者精確的多條件搜素

不好的地方 代碼不健壯 不利於維護

方法2. 大神封裝法 利用到的知識是Repository 倉庫

$fields = ['id', 'report_id', 'report_identify', 'report_first_received_date', 'drug_name', 'first_event_term', 'case_serious', 'standard_of_seriousness', 'case_causality', 'received_from_id', 'task_user_name', 'organize_role_name', 'task_countdown', 'report_countdown'];/*查詢的欄位*/$searchFields = [  'report_identify' => 'like',  'drug_name' => 'like',  'event_term' => 'like',  'organize_role_id' => '=',  'case_causality' => '=',  'report_type' => '=',  'task_user_id' => '=',  'status' => '=',];/*擷取查詢條件*/$where = $this->searchArray($searchFields);/*擷取資料*/$this->reportTaskRepo->pushCriteria(new OrderBySortCriteria('asc', 'task_countdown'));$data = $this->reportTaskRepo->findWhere($where, $fields);//在Trait裡封裝/** * 擷取請求中的參數的值 * @param array $fields [description] * @return [type]     [description] */public function searchArray($fields=[]){  $results = [];  if (is_array($fields)) {   foreach($fields as $field => $operator) {     if(request()->has($field) && $value = $this->checkParam($field, '', false)) {      $results[$field] = [$field, $operator, "%{$value}%"];     }   }  }  return $results;}

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

thinkPHP5架構實現分頁查詢步驟詳解

PHP獲得當日零點時間戳記步驟詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.