本文實(shí)例講述了Laravel5中實(shí)現(xiàn)模糊匹配加多條件查詢功能的方法。分享給大家供大家參考,具體如下:
方法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為前端傳過來的數(shù)組 利用封裝拼接進(jìn)行模糊或者精確的多條件搜素
不好的地方 代碼不健壯 不利于維護(hù)
方法2. 大神封裝法 利用到的知識(shí)是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);
/*獲取數(shù)據(jù)*/
$this->reportTaskRepo->pushCriteria(new OrderBySortCriteria('asc', 'task_countdown'));
$data = $this->reportTaskRepo->findWhere($where, $fields);
//在Trait里封裝
/**
* 獲取請(qǐng)求中的參數(shù)的值
* @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;
}
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
您可能感興趣的文章:- Laravel使用模型實(shí)現(xiàn)like模糊查詢的例子
- laravel添加角色和模糊搜索功能的實(shí)現(xiàn)代碼