In the development process, we often encounter multi-level menus , For example, the navigation bar 、 Category column, etc , It can even be an infinite menu .
The following is the role permission control , Control whether a menu can be viewed according to the database
CREATE TABLE `tb_menus` (
`menu_id` int(11) NOT NULL AUTO_INCREMENT,
`menu_name` varchar(200) NOT NULL,
`menu_level` int(11) NOT NULL,
`superior_menu_id` int(11) NOT NULL,
`menu_url` varchar(200) NOT NULL,
PRIMARY KEY (`menu_id`),
UNIQUE KEY `menu_name` (`menu_name`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8
CREATE TABLE `tb_role_menu` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`menu_id` int(11) NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=119 DEFAULT CHARSET=utf8
tb_menus The table records each menu , The key message is the menu id And parent menus id,tb_role_menu The record is role_id And menu_id Correspondence of , That is, which role can access which menu
Key code
# Here is Django Of ORM
def get_menu_tree(role_id):
menus = RoleMenu.objects.filter(role_id=role_id).values('menu_id')
menu_list = list(Menu.objects.filter(menu_id__in=menus).order_by("menu_id").values())
return generate_tree(menu_list, 0)
def generate_tree(menu_list, superior_menu_id, temp_list=None):
if temp_list is None:
temp_list = list()
tree = list()
for menu in menu_list:
if menu["menu_id"] in temp_list:
continue
if menu["superior_menu_id"] == superior_menu_id:
temp_list.append(menu["menu_id"])
menu["under_menu"] = generate_tree(menu_list, menu["menu_id"], temp_list)
tree.append(menu)
return tree
The resulting data structure is
res_menu = {
'menu_id': 1, 'menu_name': ' Authority role ', 'menu_level': 1, 'superior_menu_id': 0, 'menu_url': '',
'under_menu': [
{
},
# This list is the dictionary of the lower menu , Cycle all the time
]
...
}