赞
踩
如何实现商品二级分类
首先必须需要id,parent_id字段,其他根据需求扩展。
1.新建Category实体类
- public class Category {
- private Long id;
-
- private Long parent;
-
- private String name;
-
- private int sort;
-
- private String photoUrl;
-
- private int state;
-
- private LocalDateTime startTime;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public Long getParent() {
- return parent;
- }
-
- public void setParent(Long parent) {
- this.parent = parent;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getSort() {
- return sort;
- }
-
- public void setSort(int sort) {
- this.sort = sort;
- }
-
- public String getPhotoUrl() {
- return photoUrl;
- }
-
- public void setPhotoUrl(String photoUrl) {
- this.photoUrl = photoUrl;
- }
-
- public int getState() {
- return state;
- }
-
- public void setState(int state) {
- this.state = state;
- }
-
- public LocalDateTime getStartTime() {
- return startTime;
- }
-
- public void setStartTime(LocalDateTime startTime) {
- this.startTime = startTime;
- }
- }
2.创建数据库表sp_category
- #分类
- drop table if exists `sp_category` ;
- create table `sp_category` (
- `id` bigint not null comment 'id',
- `parent` bigint not null default 0 comment '父id',
- `name` varchar(50) not null comment '名称',
- `sort` int comment '分类顺序',
- `photo_url` varchar(50) comment '分类图片',
- `state` int comment '状态',
- `start_time` datetime comment '创建时间',
-
- primary key (`id`)
- ) engine =innodb default charset=utf8mb4 comment='分类';
3.通过父id和子id使他们联系在一起,若商品分类为一级目录,没有父目录,则父id为0 ,若为二级目录,则父id指向一级目录的id
4.若要实现tree树形结构,可以选择前端处理或者后端处理,后端处理有多种方式,我这里选择使用的是使用hutool工具实现树形结构。
5.首先导入hutool工具依赖
- <dependency>
- <groupId>cn.hutool</groupId>
- <artifactId>hutool-all</artifactId>
- <version>5.8.15</version>
- </dependency>
6.实现tree树形结构
- List<CategoryDO> nodeList=categoryMapper.all();//这里指从数据库获取的数据
- List<Tree<Long>> trees = treeUtil(nodeList);
- private List<Tree<Long>> treeUtil(List<CategoryDO> nodeList){
- //配置 这里根据自己需求设置
- TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
- treeNodeConfig.setIdKey("id");
- treeNodeConfig.setParentIdKey("parent");
- treeNodeConfig.setNameKey("name");
- //商品分类权重
- treeNodeConfig.setWeightKey("sort");
- //这里设置递归深度
- treeNodeConfig.setDeep(2);
-
- //转换器 注意这里的List<Tree<Long>>,Tree内中的泛型类型根据自己的id类型填写
- List<Tree<Long>> treeNodes = TreeUtil.build(nodeList, 0L, treeNodeConfig,
- (categoryDO, tree) -> {
- //Tree中不存在你类中的属性时候,你可以根据需求使用putExtra扩展
- tree.putExtra("id",categoryDO.getId());
- tree.putExtra("parent",categoryDO.getParent());
- tree.putExtra("name",categoryDO.getName());
- tree.putExtra("sort",categoryDO.getSort());
- tree.putExtra("photoUrl",categoryDO.getPhotoUrl());
- tree.putExtra("startTime",categoryDO.getStartTime());
- tree.put("state",categoryDO.getState());
- });
- return treeNodes;
- }
7.实现效果
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。