场景:数据库存在角色表、菜单表、角色菜单关系表,现需新增菜单,并维护角色菜单关系,因原来角色已有的菜单很多,如果通过功能操作,很费时间,想从数据库中直接维护菜单、角色菜单关系表,采取的方案如下:
表:
system_role
system_menu
system_role_menu
操作步骤:
- 菜单表中新加菜单
insert into system_menu(column1,column2,…..,columnN) values(value1,value2,……valueN)
- 建立角色表和新增菜单的关系
关键的来了:system_role、system_menu没有现成的外键关联,怎么办,没有办法了吗?不,当然有办法,咱们给新建个关联外键即可,如下
select r.id, 1 as foreign_key from system_role;
select m.id, 1 as foreign_key from system_menu;
建立两个表的关系:
select rr.id as role_id ,mm.id as menu_id
from (select r.id, 1 as foreign_key from system_role) rr
left join (select m.id, 1 as foreign_key from system_menu) mm
on mm.foreigh_key=rr.foreign_key;
- 将新建立的关系插入到角色菜单表中
最关键的来了:
insert into system_role_menu(role_id,menu_id)
select rr.id as role_id ,mm.id as menu_id
from (select r.id, 1 as foreign_key from system_role) rr
left join (select m.id, 1 as foreign_key from system_menu) mm
on mm.foreigh_key=rr.foreign_key;
如此即可完成。
如果我的文章可以帮到你,有钱的捧个钱场,没钱的捧个人场,这也是支撑我继续做下去的动力!