多级菜单(父子)结构组装或课程多级分类(父子)结构组装的思路

这里以课程多级分类为例来实现父子结构的组装

先看数据库中的存储

多级菜单(父子)结构组装或课程多级分类(父子)结构组装的思路_第1张图片

仔细看pid和path一栏可以发现有多级结构
存在子中还有子的情况

详解

使用的框架:mybatis-plus

需要注意的地方:

//实体类添加了字段后,需要加上下面注解,告诉mybatis-plus框架,表中没有这个字段,否则会报错
@TableField(exist = false)
//这里最好是直接new出来,否则后面代码很容易出错
private List<CourseType> children = new ArrayList<>();

代码

核心思路:各自找各自的父,找到后装进各自父课程类型中的children中

public List<CourseType> treeData() {
		//先查所有课程分类     null:表示没有条件
        List<CourseType> courseTypes = baseMapper.selectList(null);
        //准备集合装所有 顶级父亲(pid == 0)
        List<CourseType> topLevelParentCourseTypes = new ArrayList<>();
        //遍历所有课程分类
        for (CourseType courseType : courseTypes) {
            //判断pid,为0即为顶级父亲
            //Java里面定义的id是Long包装类型,转成long来和0比较是最准确的
            if(courseType.getPid().longValue() == 0){
                //将顶级课程分类放入集合中的CourseType中
                topLevelParentCourseTypes.add(courseType);
            } else {//非顶级课程分类,即pid不为0
                //遍历非顶级课程分类
                //核心思路:各自找各自的父,找到后装进各自父课程类型中的children中
                for (CourseType currentCourseTypes : courseTypes) {
                    //当前分类的id和某个分类的pid相等那么这一对就是父子
                    if(currentCourseTypes.getId().longValue() == courseType.getPid().longValue()){
                        //父  currentCourseTypes       子  courseType
                        //将子装进父中children里
                        currentCourseTypes.getChildren().add(courseType);
                        //成功找到一对父子并装好结构,结束该循环。
                        break;
                    }
                }
            }
            //break后,开始下一次循环找其他的父子并组装
        }
        //返回已经组装好的结构
        return topLevelParentCourseTypes;
    }

多级菜单(父子)结构组装或课程多级分类(父子)结构组装的思路_第2张图片

你可能感兴趣的:(多级菜单(父子)结构组装或课程多级分类(父子)结构组装的思路)