gogo-gormgolang-migrate

Didn't get Delete User records based on ID


I'm using Go with Gorm many2many association from User and Role tables.

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"`
}

using below code for delete user records and roles based on user 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)**

Once executed last statement but didn't get delete(no impact) records from tables users and user_roles. Kindly suggest me what is issue.


Solution

  • This code:

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

    by the Gorm documentation:

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

    You need to use the Delete with Select https://gorm.io/docs/associations.html#Delete-with-Select

    So actually it should be:

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