go 循环处理无限极数据
数据表结构:
CREATE TABLE `permission` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '权限ID',
`permission_name` varchar(255) DEFAULT NULL COMMENT '权限名称',
`permission_url` varchar(255) DEFAULT NULL COMMENT '权限路由',
`status` tinyint(1) DEFAULT NULL COMMENT '权限状态',
`pid` int(11) DEFAULT NULL COMMENT '父级ID',
`created_at` datetime(3) DEFAULT NULL,
`updated_at` datetime(3) DEFAULT NULL,
`deleted_at` datetime(3) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_permission_deleted_at` (`deleted_at`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8mb4;
代码:
//定义结构体存储数据
type Permission_c struct {
Id int
Pid int
Status int
PermissionName string
PermissionUrl string
Children []*Permission_c `gorm:"foreignKey:Pid;references:Id"`
}
// 权限列表
func (con Permission_c) PermissionList(c *gin.Context) {
var permissions []*Permission_c
if err := database.DB.Table("permission").Find(&permissions).Error; err != nil {
c.JSON(500, gin.H{
"error": err,
})
return
}
// 创建一个映射,方便快速查找每个权限节点
permissionMap := make(map[int]*Permission_c)
for _, p := range permissions {
permissionMap[p.Id] = p
}
//
var pdata []*Permission_c
for _, p := range permissions {
if p.Pid == 0 {
pdata = append(pdata, p)
} else {
// 找到父节点
parent, ok := permissionMap[p.Pid]
if ok {
if parent.Children == nil {
parent.Children = make([]*Permission_c, 0)
}
parent.Children = append(parent.Children, p)
}
}
}
c.JSON(200, gin.H{
"permission": pdata,
})
}
处理后的数据:
{
"permission": [
{
"Id": 1,
"Pid": 0,
"Status": 0,
"PermissionName": "用户管理",
"PermissionUrl": "#",
"Children": [
{
"Id": 2,
"Pid": 1,
"Status": 0,
"PermissionName": "账号管理",
"PermissionUrl": "/backendUsers/permission/list",
"Children": [
{
"Id": 5,
"Pid": 2,
"Status": 0,
"PermissionName": "账号添加",
"PermissionUrl": "/backendUsers/account/add",
"Children": null
},
{
"Id": 6,
"Pid": 2,
"Status": 0,
"PermissionName": "账号删除",
"PermissionUrl": "/backendUsers/account/del",
"Children": null
},
{
"Id": 8,
"Pid": 2,
"Status": 0,
"PermissionName": "账号修改",
"PermissionUrl": "/backendUsers/account/upd",
"Children": null
}
]
},
{
"Id": 3,
"Pid": 1,
"Status": 0,
"PermissionName": "角色管理",
"PermissionUrl": "/backendUsers/role/list",
"Children": [
{
"Id": 9,
"Pid": 3,
"Status": 0,
"PermissionName": "角色添加",
"PermissionUrl": "/backendUsers/role/add",
"Children": null
},
{
"Id": 10,
"Pid": 3,
"Status": 0,
"PermissionName": "角色删除",
"PermissionUrl": "/backendUsers/role/del",
"Children": null
},
{
"Id": 12,
"Pid": 3,
"Status": 0,
"PermissionName": "角色修改",
"PermissionUrl": "/backendUsers/role/upd",
"Children": null
}
]
},
{
"Id": 4,
"Pid": 1,
"Status": 0,
"PermissionName": "权限管理",
"PermissionUrl": "/backendUsers/permission/list",
"Children": [
{
"Id": 13,
"Pid": 4,
"Status": 0,
"PermissionName": "权限添加",
"PermissionUrl": "/backendUsers/permission/add",
"Children": null
}
]
}
]
},
{
"Id": 14,
"Pid": 0,
"Status": 0,
"PermissionName": "商品管理",
"PermissionUrl": "#",
"Children": null
}
]
}