0

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.

Ezequiel Muns
  • 7,492
  • 33
  • 57
  • The `Delete` in your last line is meant to take a slice of the related entity (a `[]Role`), you are giving it a `User`. Check out [the documentation](https://gorm.io/docs/associations.html#Delete-Associations) – Ezequiel Muns Feb 07 '21 at 15:16

1 Answers1

0

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)

  • Tried but getting error. Error 1451: Cannot delete or update a parent row: a foreign key constraint fails (`hopit_auth_db`.`use r_roles`, CONSTRAINT `FKhfh9dx7w3ubf1co1vdev94g3f` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) – Abhishek Singh Feb 06 '21 at 15:52
  • I think if you add the delete on cascade in the table it should work – Spiros I. Economakis Feb 06 '21 at 19:51