基于gin关于多级菜单的处理

多级菜单是很多业务场景需要的。下面是一种处理方式

go 复制代码
// 生成树结构
func tree(menus []*video.XkVideoCategory, parentId uint) []*video.XkVideoCategory {
	//定义子节点目录
	var nodes []*video.XkVideoCategory
	if reflect.ValueOf(menus).IsValid() {
		//循环所有一级菜单
		for _, v := range menus {
			//查询所有该菜单下的所有子菜单
			if v.ParentId == parentId {
				//特别注意压入元素不是单个所有加三个 **...** 告诉切片无论多少元素一并压入
				v.Children = append(v.Children, tree(menus, v.ID)...)
				nodes = append(nodes, v)
			}

		}
	}
	return nodes
}

下面是model

sql 复制代码
type XkVideoCategory struct {
	ID           uint      `gorm:"primarykey;comment:主键ID" json:"id" form:"id"`
	CategoryName string    `json:"categoryName" gorm:"not null;default:'';comment:分类名称"`
	Description  string    `json:"description" gorm:"not null;default:'';comment:分类描述"`
	CreateTime   time.Time `gorm:"type:datetime(0);comment:创建时间" json:"createTime"`
	UpdatedTime  time.Time `gorm:"type:datetime(0);comment:更新时间" json:"updatedTime"`
	ParentId     uint      `json:"parentId" gorm:"not null;default:0;comment:分类的主ID"`
	Status       int8      `json:"status" gorm:"not null;default:1;comment:0 未发布 1 发布"`
	Sorted       int8      `json:"sorted" gorm:"not null;default:1;comment:0 排序"`
	IsDelete     int8      `json:"isDelete" gorm:"not null;default:0;comment:0 未删除 1 删除"`
	// 忽略该字段,- 表示无读写,-:migration 表示无迁移权限,-:all 表示无读写迁移权限
	Children []*XkVideoCategory `gorm:"-" json:"children"`
}
相关推荐
会编程的土豆6 分钟前
Gin 核心概念速记
数据库·后端·gin·goland
GDAL1 小时前
Gin c.HTML 完整教程
html·gin
会编程的土豆3 小时前
Gin 核心概念 & 前后端交互笔记
笔记·交互·gin
会编程的土豆4 小时前
Gin 中 `c.BindJSON` 与 `c.JSON` 详细讲解
c语言·json·gin
会编程的土豆4 小时前
Gin 核心对象:`c *gin.Context` 详细解析
服务器·c语言·gin
会编程的土豆4 小时前
Gin POST 请求完整流程笔记
chrome·笔记·gin
lolo大魔王2 天前
Go 后端实战|Gin + GORM V2 + MySQL 企业级 API 项目开发(完整版)
mysql·golang·gin
lolo大魔王2 天前
Go 语言 Web 框架 Gin 入门详解
前端·golang·gin
栈溢出了3 天前
GIN学习笔记
人工智能·神经网络·算法·机器学习·gin
会编程的土豆6 天前
Gin 框架第一课:从 0 搞懂 Gin 最基础的路由
数据库·sql·gin·goland