原文地址 http://www.niu12.com/article/37node
數據表以下golang
-- ---------------------------- -- 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)json
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 }