You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
59 lines
1.9 KiB
59 lines
1.9 KiB
package model
|
|
|
|
import (
|
|
"context"
|
|
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// RoleMenu 角色-菜单关联
|
|
type RoleMenu struct {
|
|
Id int64 `gorm:"column:id;primaryKey;autoIncrement" json:"id"`
|
|
RoleId int64 `gorm:"column:role_id;index" json:"roleId"`
|
|
MenuId int64 `gorm:"column:menu_id;index" json:"menuId"`
|
|
}
|
|
|
|
func (RoleMenu) TableName() string {
|
|
return "role_menu"
|
|
}
|
|
|
|
// RoleMenuFindByRoleId 获取角色的菜单ID列表
|
|
func RoleMenuFindByRoleId(ctx context.Context, db *gorm.DB, roleId int64) ([]int64, error) {
|
|
var menuIds []int64
|
|
err := db.WithContext(ctx).Model(&RoleMenu{}).Where("role_id = ?", roleId).Pluck("menu_id", &menuIds).Error
|
|
return menuIds, err
|
|
}
|
|
|
|
// RoleMenuFindByRoleIds 获取多个角色的菜单ID列表(去重)
|
|
func RoleMenuFindByRoleIds(ctx context.Context, db *gorm.DB, roleIds []int64) ([]int64, error) {
|
|
var menuIds []int64
|
|
if len(roleIds) == 0 {
|
|
return menuIds, nil
|
|
}
|
|
err := db.WithContext(ctx).Model(&RoleMenu{}).Where("role_id IN ?", roleIds).Distinct("menu_id").Pluck("menu_id", &menuIds).Error
|
|
return menuIds, err
|
|
}
|
|
|
|
// RoleMenuSetForRole 全量设置角色的菜单(先删后插)
|
|
func RoleMenuSetForRole(ctx context.Context, db *gorm.DB, roleId int64, menuIds []int64) error {
|
|
return db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
|
// 删除旧关联
|
|
if err := tx.Where("role_id = ?", roleId).Delete(&RoleMenu{}).Error; err != nil {
|
|
return err
|
|
}
|
|
// 插入新关联
|
|
if len(menuIds) == 0 {
|
|
return nil
|
|
}
|
|
records := make([]RoleMenu, 0, len(menuIds))
|
|
for _, menuId := range menuIds {
|
|
records = append(records, RoleMenu{RoleId: roleId, MenuId: menuId})
|
|
}
|
|
return tx.Create(&records).Error
|
|
})
|
|
}
|
|
|
|
// RoleMenuDeleteByRoleId 删除角色的所有菜单关联
|
|
func RoleMenuDeleteByRoleId(ctx context.Context, db *gorm.DB, roleId int64) error {
|
|
return db.WithContext(ctx).Where("role_id = ?", roleId).Delete(&RoleMenu{}).Error
|
|
}
|
|
|