【问题标题】:Didn't get Delete User records based on ID没有得到基于 ID 的删除用户记录
【发布时间】:2021-05-10 16:01:39
【问题描述】:

我正在使用 Go 与来自用户和角色表的 Gorm many2many 关联。

type User struct {
    //gorm.Model
    ID               int64          `json:"id" gorm:"primary_key"`
    Active           sql.NullString ` json:"active " `
    Email            string         `json:"email"`
    FullName         string         `json:"full_name"`
    Password         string         `json:"password"`
    Username         string         `json:"username"`
    Groups           string         `json:"groups"`
    Otp              string         `json:"otp"`
    CreatedTimeStamp time.Time      `json:"created_time_stamp"`
    UpdateTimeStamp  time.Time      `json:"update_time_stamp"`
    LastLogin        time.Time      `json:"last_login"`
    UserCount        uint           `json:"user_count" `
    Roles            []Role         `gorm:"many2many:user_roles;"`
}

type Role struct {
    //gorm.Model
    ID    int64  `json:"id" gorm:"primary_key"`
    Name  string `json:"name"`
    Users []User `gorm:"many2many:user_roles"`
}

使用以下代码根据用户 ID 删除用户记录和角色。

var roles []Role
db.Model(Role{}).Where("Name = ?", "ROLE_ADMIN").Take(&roles)
newUser := &User{
    Email: user.Email, 
    FullName: user.FullName, 
    Username: user.Username, 
    Groups: groupCreation(user.Username), 
    Password: EncodePassword(user.Password), 
    CreatedTimeStamp: time.Now(), 
    UpdateTimeStamp: time.Now(), 
    LastLogin: time.Now(), 
    Roles: roles
}

db.Save(newUser)

**db.Model(&user).Association("Role").Delete(&newUser)**

一旦执行了最后一条语句,但没有从表用户和用户角色中删除(无影响)记录。 请建议我有什么问题。

【问题讨论】:

  • 你最后一行中的Delete 是为了获取相关实体的一部分([]Role),你给它一个User。查看the documentation

标签: go go-gorm golang-migrate


【解决方案1】:

这段代码:

db.Model(&user).Association("Role").Delete(&newUser)

由 Gorm 文档提供:

Remove the relationship between source & arguments if exists, only delete the reference, won’t delete those objects from DB.

您需要使用Delete with Select https://gorm.io/docs/associations.html#Delete-with-Select

所以实际上应该是:

db.Select("Role").Delete(&newUser)

【讨论】:

  • 已尝试但出现错误。错误 1451:无法删除或更新父行:外键约束失败 (hopit_auth_db.use r_roles, CONSTRAINT FKhfh9dx7w3ubf1co1vdev94g3f FOREIGN KEY (user_id) REFERENCES users (id))
  • 我认为如果您在表中的级联上添加删除它应该可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2021-01-29
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多