我发现了一些理解文档的问题。我有 Go 的 REST API,我尝试创建一个端点,我只需要按角色提取用户。我尝试了不同的解决方案,但无法实现我所需要的。这就是我所做的,我不确定如何继续,所以我只能通过确切的角色来获取用户。如果有人可以帮助我,我们将不胜感激,因为我在文档中找不到更高级的东西。
来自此端点的 JSON 响应是:
[
{
"ID": 1,
"CreatedAt": "2020-12-09T14:40:55.171011+02:00",
"UpdatedAt": "2020-12-09T14:40:55.175537+02:00",
"DeletedAt": null,
"email": "h@go.com",
"password": "$2a$14$KN2wAOnfecAriBW0xeAJke.okEUlcpDHVeuk",
"bearer": "eyJhbGciOiJIUzI1NiIs2lhdCI6MTYwNjMwNTEzNn0.J2wBp8ecA9TebP6L73qZ1OZmo02DwQy9vTySt0fil4c",
"first_name": "H",
"last_name": "Pro",
"phone": "353456",
"salesforce_id": "sfsdddfsdf",
"webflow_id": "wfwfwfaawfw",
"Roles": null
},
{
"ID": 2,
"CreatedAt": "2020-12-09T14:40:55.171011+02:00",
"UpdatedAt": "2020-12-09T14:40:55.175537+02:00",
"DeletedAt": null,
"email": "s@go.com",
"password": "$2wAOnfecAriBW0xeAJke.okEUlcpDHVeuk",
"bearer": "eyJhbGiIs2lhdCI6MTYwNjMwNTEzNn0.J2wBp8ecA9TebP6L73qZ1OZmo02DwQy9vTy0fil4c",
"first_name": "S",
"last_name": "Test",
"phone": "3556",
"salesforce_id": "sfsdf",
"webflow_id": "wfwfwfw",
"Roles": null
}
]
用户结构:
type User struct {
gorm.Model
Email string `json:"email"`
Password string `json:"password"`
Token string `json:"bearer"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Phone string `json:"phone"`
SalesforceID string `json:"salesforce_id"`
WebflowID string `json:"webflow_id"`
Roles []*Roles `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;many2many:user_roles;"`
}
角色结构:
type Roles struct {
gorm.Model
Name string `json:"name"`
Users []*User `gorm:"many2many:user_roles"`
}
我在 Postgre 中创建并适用于我的案例的 sql 查询:
SELECT * FROM users
JOIN user_roles ON users.id = user_roles.user_id
JOIN roles ON user_roles.roles_id = roles.id
WHERE user_roles.roles_id = 1
拉风的咖菲猫
相关分类