这次给大家带来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;
}
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
thinkphp5框架实现分页查询步骤详解
php获得当日零点时间戳步骤详解
以上就是laravel5实现模糊匹配加多条件查询功能实现步骤详解的详细内容。