我想创建一个数据,然后返回该值,但该值与另一个表相关。
用户响应结构
type UserRespone struct {
ID int `json:"id,omitempty"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Address string `json:"address"`
Roles []roles.Roles `json:"roles" gorm:"many2many:users_roles;foreignKey:ID;joinForeignKey:UserID;references:ID;joinReferences:RolesID"`
}
角色结构
type Roles struct {
ID int `json:"id" gorm:"<-:false;primaryKey"`
Name string
}
这是一个创建数据的函数,我想返回值[]roles.Roles
func (r *UserRepositoryImpl) AuthSignUp(ctx context.Context, req user.AuthSignUp) (user.UserRespone, error) {
createdUser := req.ToUser()
hashPassword, _ := bcrypt.GenerateFromPassword([]byte(createdUser.Password), bcrypt.DefaultCost)
createdUser.Password = string(hashPassword[:])
result := r.Db.
WithContext(ctx).
Create(&createdUser)
for _, rolesID := range req.RolesID {
userRole := new(user.UsersRoles)
userRole.UserID = createdUser.ID
userRole.RolesID = rolesID
result = r.Db.WithContext(ctx).Create(&userRole)
}
return createdUser.ToResponse(), result.Error
}
我想返回这样的值:
user.UserResponse{
ID: 4,
Email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="94e4e1e0e6fda0d4f3f9f5fdf8baf7fbf9" rel="noreferrer noopener nofollow">[email protected]</a>",
FirstName: "putri",
LastName: "cantik",
Address: "bonang",
Roles: []roles.Roles{
{
ID: 1,
Name: "Admin",
},
{
ID: 2,
Name: "Consumer",
},
},
}
但是当我创建数据集时,我只能得到如下值:
user.UserRespones{
ID: 4,
Email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5d5d0d1d7cc91e5c2c8c4ccc98bc6cac8" rel="noreferrer noopener nofollow">[email protected]</a>",
FirstName: "putri",
LastName: "cantik",
Address: "bonang",
Roles: []roles.Roles(nil),
}
最佳答案
据我所知,您已经拥有用户数据和角色 ID。我想您也只是想获取角色名称:
err := r.db.Find(&createdUser.Roles, req.RolesID)
// err handling
也就是说,你的类型和名称有点不清楚。 UserRespone
(注意拼写错误)可能应该命名为 DBUser
- 无论它是用作响应还是其他东西并不重要,它代表用户的数据库条目,对吗?
此外,我只能对 createdUser
和 UsersRoles
的类型和字段做出假设,因此我可能错过了一些东西。
我认为 createdUser
的类型是 UserRespone
- 但我希望 Roles
已经完成(并且您不必查询任何东西)。如果没有,那么您应该为此引入一种新类型,例如RequestUser
(与DBUser
相对),仅包含Role
ID,但不包含Role
名称。将请求中的数据、数据库条目和响应数据压缩为同一类型是令人困惑的(并且对我来说耦合有点太紧密)。
关于Gorm 创建并返回值 Many2many,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74411293/