Home > PHP Framework > ThinkPHP > Use of ThinkPHP6 search engine

Use of ThinkPHP6 search engine

wpj
Release: 2020-05-07 10:32:49
Original
233 people have browsed it

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.

1. Create the Admin.php model in the app\model directory

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).

<?php

namespace app\model;

use think\Exception;
use think\Model;

class Admin extends Model
{

    //查询数据(数据表格)
    public static function getByData($limit=&#39;10&#39;,$order=&#39;id desc&#39;,$field=&#39;*&#39;,$search=[],$searchKey=[])
    {
        try {
            //查询数据
            $result = self::withSearch($searchKey,$search)->order($order)->field($field)->paginate(request()->get(&#39;limit&#39;,$limit))->toArray();
        }catch (\Exception $e){
            throw new Exception(&#39;数据库内部错误!&#39;);
        }
        //返回格式为json的数据
        return json([
            &#39;code&#39;  =>  0,
            &#39;msg&#39;   =>  &#39;数据请求成功&#39;,
            &#39;count&#39; =>  $result[&#39;total&#39;],
            &#39;data&#39;  =>  $result[&#39;data&#39;]
        ]);
    }

    /**
     * @desc 查询用户名
     * @param $query    查询对象
     * @param $value    搜索的值
     * @param $data     搜索数据(可忽略)
     */
    public function searchUsernameAttr($query, $value, $data)
    {
        $query->where(&#39;username&#39;,&#39;like&#39;, &#39;%&#39; . $value . &#39;%&#39;);
    }

    /**
     * @desc 添加时间范围查询
     * @param $query
     * @param $value
     */
    public function searchCreateTimeAttr($query, $value)
    {
        $query->whereBetweenTime(&#39;create_time&#39;, $value[0], $value[1]);
    }
}
Copy after login

2. Create the Admin.php controller in the app\controller directory.

<?php

namespace app\controller;

use app\BaseController;

use app\model\Admin as AdminModel;

class Admin extends BaseController
{
    //渲染页面
    public function index()
    {
        return view();
    }

    //数据表格接口
    public function data()
    {
        //存放搜索条件
        $search = [];

        //接收前台查询传递过来的参数
        $username = request()->param(&#39;username&#39;,&#39;&#39;,&#39;trim&#39;);
        $create_time  = request()->param(&#39;create_time&#39;,&#39;&#39;,&#39;trim&#39;);

        //如果参数不为空,把数据赋值给$search
        if (!empty($username)){
            $search[&#39;username&#39;] = $username;
        }
        if (!empty($create_time)){
            $search[&#39;create_time&#39;] = explode(&#39;~&#39;,$create_time);
        }

        //获取$search[] 中的key
        $searchKey = [];

        if (!empty($search)){
            $searchKey = array_keys($search);
        }

        return AdminModel::getByData(10,&#39;id desc&#39;,&#39;*&#39;,$search,$searchKey);
    }
}
Copy after login

3. Rendering View

3.1. Execute the following command in the project directory:

composer require topthink/think-view
Copy after login

3.2. Create the index.html file in the app\view\admin folder

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>搜索器</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="https://heerey525.github.io/layui-v2.4.3/layui-v2.4.4/css/layui.css"  media="all">
    <script src="https://heerey525.github.io/layui-v2.4.3/layui-v2.4.4/layui.js" charset="utf-8"></script>
    <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>

<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <!-- 搜索框 -->
                <div class="layui-card-body" style="padding-bottom: 0;">
                    <div class="layui-form">
                        <div class="layui-inline layui-show-xs-block">
                            <input type="text" id="username" name="username" placeholder="请输入用户名" autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <input type="text" id="test1" name="create_time" placeholder="请选择时间范围" autocomplete="off" class="layui-input">
                        </div>
                        <div class="layui-inline layui-show-xs-block">
                            <button class="layui-btn" id="search"><i class="layui-icon">&#xe615;</i></button>
                        </div>
                    </div>
                </div>
                <div class="layui-card-body ">
                    <!--数据表格-->
                    <table id="dataTable" lay-filter="dataTable"></table>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script>
    layui.use([&#39;layer&#39;,&#39;table&#39;,&#39;form&#39;,&#39;laydate&#39;],function () {
        var layer = layui.layer,form = layui.form,table = layui.table, laydate = layui.laydate;

        //日期时间范围 搜索
        laydate.render({
            elem: &#39;#test1&#39;
            , type: &#39;datetime&#39;
            , range: &#39;~&#39;
        });

        //用户表格初始化
        var dataTable = table.render({
            elem: &#39;#dataTable&#39;
            ,url: "/admin/data" //数据接口
            ,page: true //开启分页
            ,toolbar: "#toolbarTpl"
            ,cols: [[ //表头
                {checkbox: true,fixed: &#39;left&#39;}
                ,{field: &#39;id&#39;, title: &#39;ID&#39;, sort: true,width:70}
                ,{field: &#39;username&#39;, title: &#39;用户名&#39;}
                ,{field: &#39;create_time&#39;, title: &#39;添加时间&#39;,width:160}
            ]]
        });

        //搜索
        $("#search").click(function () {
            var username = $("#username").val();
            var create_time = $("#test1").val();
            dataTable.reload({
                where:{username:username,create_time:create_time},
                page:{curr:1}
            });
        });
    });
</script>
</html>
Copy after login

4. Search demonstration

Use of ThinkPHP6 search engine

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template