一般来说要实现 搜索栏 的多条件搜索功能,传统我们是使用where数组条件添加的
注意TP5.1的where数组格式 和TP5.0不同 (大坑!)
$title = Request::param('title'); $start = $this->request->start_time; $end = $this->request->end_time; $where[] = ['status', '=', '1']; //初始查询条件 if (!empty($start) && !empty($end)) { $where[] = [ ['create_time', 'between time', [intval($start), intval($end)]], //添加时间查询 ]; } if (!empty($title)) { $where[] = [ ['title', 'like', '%' . $title . '%'], //添加标题查询 ]; } $list = NewsModel():: field("id,title,create_time") ->where($where) ->order('create_time desc') ->select();
使用搜索器,但时间 和 值为单独0 的查询建议用where[ ]
先在模型定义
//定义搜索器 public function searchTitleAttr($query,$value,$data) { return $value ? $query->where('title','like','%'.$value.'%') : "" ; }
控制器中使用 搜索器 + where数组
public function test( ) { $limit = $this->request->limit ?? 9999; $page = $this->request->page ?? 1; $start = $this->request->start_time; $end = input('end_time'); $title = $this->request->title; $where[] = ['status', '=', '1']; if (!empty($time1) && !empty($time2)) { // 时间搜索 $where[] = [ ['create_time', 'between time', [intval($start), intval($end)]], ]; } $list = ProductModel::alias('a') ->leftJoin('class b', 'a.class_id = b.id') ->where($where) ->field('a.id,class_id,title,imgs_url,b.type_name') ->withSearch(['title'], [ 'title' => $title, ]) ->order('a.id desc') ->limit($limit)->page($page) ->select()->toArray(); return jsonApi($list,'查询成功'); }
Join联表查询也可以使用
public function test() { $class_id = $this->request->class_id; $title = $this->request->title; $list = ProductModel::alias('a') ->leftJoin('classification b', 'a.class_id = b.id') ->where('a.class_id = b.id') ->field('a.id,class_id,title,b.type_name') ->withSearch(['class_id', 'title'], [ //哪个表的字段就在哪个模型定义搜索器 'class_id' => $class_id, 'title' => $title, ]) ->order('a.id desc') ->select()->toArray(); return $list; }