gorm-多对多查询关联实体

type Role struct {
	ID          uint          `gorm:"id"`
	Name        string        `json:"name"`
	Users       []User        `gorm:"many2many:user_roles;"`       // many-to-many relationship
	Permissions []Permission `gorm:"many2many:role_permissions;"` // many-to-many relationship
}

type Permission struct {
	gorm.Model
	Name     string `json:"name"`
	Describe string `json:"describe"`
	Type     string `json:"type"`
}

type APIPermission struct {
	ID   uint   `gorm:"id"`
	Name string `json:"name"`
	Type string `json:"type"`
}

// GetPermissionsByRoleNames 通过用户角色名获取权限
func GetPermissionsByRoleNames(db *gorm.DB, roleNames []string) ([]APIPermission, error) {
	var permissions []APIPermission
	var roles []Role
	err := db.Where("name in (?)", roleNames).Find(&roles).Error
	err = db.Model(&roles).Association("Permissions").Find(&permissions)
	return permissions, err
}

你可能感兴趣的:(go/golang,进阶教程,go,golang,后端)