type RoleHasPermissionList struct {
model.Roles
Rolehaspermissions []CUS_Rolehaspermissions `json:"rolehaspermissions" gorm:"foreignkey:role_id; references:id"`
}
type CUS_Rolehaspermissions struct {
PermissionId int `json:"-"`
RoleId int `json:"-"`
PermissinInfo model.Permission `gorm:"foreignkey:id; references:permission_id"`
}
func (CUS_Rolehaspermissions) TableName() string {
return "RoleHasPermissions"
}
type FormaterResult struct {
model.Roles
Permission []model.Permission `json:"permission"`
}
func GetRoleList(c *gin.Context) serializer.Response {
var req GetRoleListRequest
c.ShouldBind(&req)
var total int64
var list []RoleHasPermissionList
page := req.Page
pageSize := req.PageSize
model.DB.
Scopes(util.Paginate(c, page, pageSize)).
Preload("Rolehaspermissions.PermissinInfo").
Find(&list).Offset(-1).Limit(-1).Count(&total)
// 重新整理輸出格式
var formater_result []FormaterResult
for i, v := range list {
formater_result = append(formater_result, FormaterResult{Roles: v.Roles})
for _, v2 := range v.Rolehaspermissions {
formater_result[i].Permission = append(formater_result[i].Permission, v2.PermissinInfo)
}
}
return serializer.Response{
Code: 0,
Message: "成功",
Data: util.Pagination(c, page, pageSize, total, formater_result),
}
}
{
"id": 1,
"name": "company",
"display_name": "公司",
"guard_name": "admin_api",
"created_at": "2020-03-26 14:34:25",
"updated_at": "2020-03-26 14:34:25",
"permission": [
{
"id": 1,
"name": "add company",
"display_name": "add company",
"guard_name": "admin_api",
"created_at": "2020-03-26 14:34:25",
"updated_at": "2020-03-26 14:34:25"
},
{
"id": 2,
"name": "edit company",
"display_name": "edit company",
"guard_name": "admin_api",
"created_at": "2020-03-26 14:34:25",
"updated_at": "2020-03-26 14:34:25"
},
]
},
...