The model searcher function is added in ThinkPHP5.1.22. The function of the searcher is to encapsulate the query condition expression of the field (or search identifier). A searcher corresponds to a special method (the method must be of public type). The method naming convention is: searchFieldNameAttr.
Searcher scenarios include:
Restrict and standardize the search conditions of the form;
Predefined query conditions simplify the query ;
Comparison of searchers:
Searchers usually compare with the query range. No matter how many searchers are defined, they only need to be done once. Call, the query range needs to be called multiple times if you need to combine queries.
The getByData() method defined in the Admin model is used to query data and return it in JSON format. Because our front-end uses LayUI's data table. The two methods searchUsernameAttr() and searchCreateTimeAttr() are exactly the searcher naming convention: searchFieldNameAttr, FieldName is the camel case conversion of the data table field, and the searcher is only triggered when the withSearch method is called. The searcher method has three parameters, the first is the query object, the second is the value of the current search identifier, and the third is all current search data (optional).
order($order)->field($field)->paginate(request()->get('limit',$limit))->toArray(); }catch (\Exception $e){ throw new Exception('数据库内部错误!'); } //返回格式为json的数据 return json([ 'code' => 0, 'msg' => '数据请求成功', 'count' => $result['total'], 'data' => $result['data'] ]); } /** * @desc 查询用户名 * @param $query 查询对象 * @param $value 搜索的值 * @param $data 搜索数据(可忽略) */ public function searchUsernameAttr($query, $value, $data) { $query->where('username','like', '%' . $value . '%'); } /** * @desc 添加时间范围查询 * @param $query * @param $value */ public function searchCreateTimeAttr($query, $value) { $query->whereBetweenTime('create_time', $value[0], $value[1]); } }
param('username','','trim'); $create_time = request()->param('create_time','','trim'); //如果参数不为空,把数据赋值给$search if (!empty($username)){ $search['username'] = $username; } if (!empty($create_time)){ $search['create_time'] = explode('~',$create_time); } //获取$search[] 中的key $searchKey = []; if (!empty($search)){ $searchKey = array_keys($search); } return AdminModel::getByData(10,'id desc','*',$search,$searchKey); } }
3.1. Execute the following command in the project directory:
composer require topthink/think-view
3.2. Create the index.html file in the app\view\admin folder
The above is the detailed content of Use of ThinkPHP6 search engine. For more information, please follow other related articles on the PHP Chinese website!