我们在开发过程中经常面对多对多的情况,那么我们应该怎么做呢?在实际工作中,权限和角色符合一对多的情况,下面我就一简单的RBAC做个简单示例。 权限表
- 一个权限对应多个角色
- 一个角色拥有多个权限
- 通过一个中间表进行关联
package models
type Permission struct {ModelPath string `json:"path"`Title string `json:"title"`ApiPath string `json:"apiPath"`ParentId uint `json:"parentId" gorm:"default:0"`Icon string `json:"icon"`}
角色表
代码语言:javascript复制package models
type Role struct {ModelRoleName string `json:"roleName"`Description string `json:"description"`//不同步更新permission表//Permission []Permission `json:"permission" gorm:"many2many:role_permissions;association_autoupdate:false;association_autocreate:false"`//同步更新permission表Permission []Permission `json:"permission" gorm:"many2many:role_permissions"`}
权限角色关联表
代码语言:javascript复制package models
type RolePermission struct {ModelRoleId uint `json:"roleId"`PermissionId uint `json:"permissionId"`}
示例
代码语言:javascript复制package main
import ("ginLearn.com/models")
func main() {db := models.DB()role := models.Role{}role.ID = 8var permissionSlice []models.Permission//根据角色查询所有权限//SELECT `permissions`.* FROM `permissions` INNER JOIN `role_permissions`//ON `role_permissions`.`permission_id` = `permissions`.`id`//WHERE `permissions`.`deleted_at` IS NULL AND ((`role_permissions`.`role_id` IN (8)))db.Model(&role).Related(&permissionSlice, "permission")
//我们更新角色的所有权限该怎么做呢?//1、删除角色的所有的权限db.Where("role_id=?", role.ID).Unscoped().Delete(&models.RolePermission{})//2、给角色赋予权限role.Permission = []models.Permission{permissionSlice[0]}//更新角色的权限//UPDATE `roles` SET `updated_at` = '2020-03-24 01:14:17', `deleted_at` = NULL, `role_name` = '', `description` = '' WHERE `roles`.`deleted_at` IS NULL AND `roles`.`id` = 8//UPDATE `permissions` SET `updated_at` = '2020-03-24 01:14:17', `deleted_at` = NULL, `path` = '', `title` = '仪表盘', `api_path` = '', `parent_id` = 0, `icon` = 'el-icon-monitor//' WHERE `permissions`.`deleted_at` IS NULL AND `permissions`.`id` = 1//INSERT INTO `role_permissions` (`role_id`,`permission_id`) SELECT 8,1 FROM DUAL WHERE NOT EXISTS (SELECT * FROM `role_permissions` WHERE `role_id` = 8 AND `permission_id` = 1)db.Save(&role)}
在这里,我们演示了多对多关系下的查询和修改,通过角色找到权限;更新角色权限。例外附上了测试的SQL和数据库。需要的小伙伴自行下载。 链接:https://pan.baidu.com/s/1OE-6jhPjF2VEvS1KfMiufQ 提取码:xxq0