JonB
JonB

Reputation: 814

Gorm many-to-many relationship, permanent delete of record inside a for-loop not working

I have a join table that holds relationship between users and projects in my program. I have an update endpoint that tries to add projects to users, if they are already not present, otherwise it will remove the correlation. I'm not able to permanently delete the record. I've tried to use both recommended methods

// UserProjects join table for linking projects to users.
type UserProjects struct {
    UserID          uint
    ProjectID       uint
}

func updateUserProjects(db *gorm.DB, userID uint, projects []Project) error {
    for _, project := range projects {
        userProject := UserProjects{
            UserID:     userID,
            ProjectID:  project.ID,
        }
        dump.P(userProject)

        result := db.Debug().Create(userProject)
        if result.Error != nil {
            // record already exists in db, will be removed instead of being inserted.
            if result.Error.(*mysql.MySQLError).Number == 1062 {
                //if result := db.Debug().Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(&userProject); result.Error != nil {
                if result := db.Debug().Unscoped().Delete(&userProject); result.Error != nil {
                    dump.P(result.Error)
                }
                fmt.Println("project was not inserted, but instead removed!")
                continue
            }
            fmt.Println("sql create error return")
        }
        fmt.Println("project attached to user")
    }

    return nil
}
mysql> desc user_projects;
+------------+-----------------+------+-----+---------+-------+
| Field      | Type            | Null | Key | Default | Extra |
+------------+-----------------+------+-----+---------+-------+
| user_id    | bigint unsigned | NO   | PRI | NULL    |       |
| project_id | bigint unsigned | NO   | PRI | NULL    |       |
+------------+-----------------+------+-----+---------+-------+

Error when using Unscoped() WHERE conditions required

And no error when using Session(&gorm.Session{AllowGlobalUpdate: true})

Upvotes: 1

Views: 442

Answers (1)

user19812413
user19812413

Reputation:

gorm complains with Unscoped() because it cannot form any query to delete with your current UserProjects struct without a where clause (No gorm tags).

declare this with relevant tags, atleast primaryKey and Unscoped() delete will work.

type UserProjects struct {
    UserID    uint `gorm:"primaryKey"`
    ProjectID uint `gorm:"primaryKey"`
}

Upvotes: 0

Related Questions