Skip to content

新增搜索

liaofei edited this page Jan 20, 2021 · 1 revision

如何快速的新增搜索,在这之前我们先要了解thinkphp的搜索器,搜索器的作用是用于封装字段(或者搜索标识)的查询条件表达式,一个搜索器对应一个特殊的方法(该方法必须是public类型),方法命名规范为:searchFieldNameAttr,具体的详情可以参考ThinkPHP开发文档

我们在程序上又对搜索器做了更为便捷的封装,可以大大节省你的开发时间,接下来我们以【内容】【文章管理】列表为实例,讲解如何快速的增加一个搜索。

文章管理接口控制器

控制器: app/adminapi/controller/v1/cms/Article.php
方法:  public function index()

文章管理数据表字典

CREATE TABLE `eb_article` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '文章管理ID',
  `cid` varchar(255) DEFAULT '1' COMMENT '分类id',
  `title` varchar(255) NOT NULL DEFAULT '' COMMENT '文章标题',
  `author` varchar(255) DEFAULT NULL COMMENT '文章作者',
  `image_input` varchar(255) NOT NULL DEFAULT '' COMMENT '文章图片',
  `synopsis` varchar(255) DEFAULT NULL COMMENT '文章简介',
  `share_title` varchar(255) DEFAULT NULL COMMENT '文章分享标题',
  `share_synopsis` varchar(255) DEFAULT NULL COMMENT '文章分享简介',
  `visit` varchar(255) DEFAULT '0' COMMENT '浏览次数',
  `sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序',
  `url` varchar(255) DEFAULT NULL COMMENT '原文链接',
  `status` tinyint(1) unsigned NOT NULL DEFAULT '1' COMMENT '状态',
  `add_time` varchar(255) NOT NULL DEFAULT '' COMMENT '添加时间',
  `hide` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否隐藏',
  `admin_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '管理员id',
  `mer_id` int(10) unsigned DEFAULT '0' COMMENT '商户id',
  `product_id` int(10) NOT NULL DEFAULT '0' COMMENT '商品关联id',
  `is_hot` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否热门(小程序)',
  `is_banner` tinyint(1) unsigned NOT NULL DEFAULT '0' COMMENT '是否轮播图(小程序)',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='文章管理表';

如下图我们可以看出列表上只有文章类型搜索和文章搜索。那么我们先增加一个时间搜索,增加一个浏览量范围搜索。

输入图片说明

一,加入时间搜索。

前端调用时间组件

输入图片说明

后端index方法接收参数 ['data', '', '', 'time']

输入图片说明

到这里我们就可以根据‘add_time’来进行时间筛选。因为关于‘add_time’字段时间搜索我们已在“crmeb/traits/ModelTrait.php”做封装,不需要再在具体的model里面写搜索器。直接按照以上方式调用就好。

二,加入范围搜索器

比如搜索浏览量大于3小于30的文章。浏览量字段‘visit’。

1,后端index方法接收参数 ['visit', '3,30'], 然后将'3,30'转化为数组,['visit', [3,30]] 2,然后将整个where搜索条件传入查询列表的方法中

 $data = $this->service->getList($where);

3,在dao层调用查询方法,切记要用搜索器查询方法一定要用search,不能用where(),否则搜索器是不生效的。

文件位置:app/dao/article/ArticleDao.php

 public function getList(array $where, int $page, int $limit)
    {
        return $this->search($where)->with(['content', 'storeInfo', 'cateName'])->page($page, $limit)->order('sort desc,id desc')->select()->toArray();
    }

4,在model中加入浏览量搜索器 searchVisitAttr

public function searchVisitAttr($query, $value, $data)
    {
        if ($value) {
            if (is_array($value)) {
                $query->whereBetween('visit', $value)
            }else{
                $query->where('visit', $value);
            }

        }
    }

至此一个完整的搜索流程就结束,其他字段搜索参考以上流程即可。

Clone this wiki locally