golang实现无限级菜单

golang实现无限级菜单

原文地址  http://www.niu12.com/article/37

golang实现无限级菜单(beego框架下)

数据表如下

-- ----------------------------
-- Table structure for `auth_menu`
-- ----------------------------
DROP TABLE IF EXISTS `auth_menu`;
CREATE TABLE `auth_menu` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`pid` int(11) NOT NULL COMMENT '父级菜单id',
`name` char(20) NOT NULL COMMENT '菜单名单',
`sort` tinyint(4) DEFAULT '0' COMMENT '排序值',
`route` varchar(60) DEFAULT '' COMMENT '跳转链接',
PRIMARY KEY (`id`),
KEY `pid` (`pid`)
) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8mb4 COMMENT='权限管理_菜单表'; -- ----------------------------
-- Records of auth_menu
-- ----------------------------
INSERT INTO `auth_menu` VALUES ('14', '0', '设置', '1', '');
INSERT INTO `auth_menu` VALUES ('15', '14', '权限管理', '1', '');
INSERT INTO `auth_menu` VALUES ('16', '14', '我的设置', '2', '');
INSERT INTO `auth_menu` VALUES ('18', '15', '角色列表', '2', '/auth/role');
INSERT INTO `auth_menu` VALUES ('19', '15', '权限列表', '3', '/auth/permission');
INSERT INTO `auth_menu` VALUES ('20', '15', '行为列表', '4', '/auth/action');
INSERT INTO `auth_menu` VALUES ('21', '15', '菜单列表', '5', '/auth/menu');
INSERT INTO `auth_menu` VALUES ('22', '16', '基本信息', '1', '/administrator/adminInfo');
INSERT INTO `auth_menu` VALUES ('23', '15', '管理员列表', '8', '/auth/administrator');

文件 menu.go (使用beego orm)

type Menu struct {
Id int `json:"id"`
Pid int `json:"pid"`
Name string `json:"name"`
Sort int `json:"sort"`
Route string `json:"route"`
} type TreeList struct {
Id int `json:"id"`
Name string `json:"name"`
Pid int `json:"pid"`
Sort int `json:"sort"`
Route string `json:"route"`
Children []*TreeList `json:"children"`
} func init() {
// 注册模型
orm.RegisterModel(new(Menu))
} func (m *Menu)TableName() string {
return "auth_menu"
} /**
菜单列表
*/
func (m *Menu)MenuList() []*TreeList{
return m.getMenu(0)
} /**
递归获取树形菜单
*/
func (m *Menu)getMenu(pid int) []*TreeList {
o := orm.NewOrm()
var menu []Menu
_,_ = o.QueryTable("auth_menu").Filter("pid", pid).OrderBy("sort").All(&menu)
treeList := []*TreeList{}
for _, v := range menu{
child := v.getMenu(v.Id)
node := &TreeList{
Id:v.Id,
Name:v.Name,
Sort:v.Sort,
Route:v.Route,
Pid:v.Pid,
}
node.Children = child
treeList = append(treeList, node)
}
return treeList
}
05-11 22:56