Matthew S
Matthew S

Reputation: 1040

Golang Gorm: Is it possible to delete a record via a many2many relationship?

I have a many2many structure similar to GORM's example:

// User has and belongs to many languages, use `user_languages` as join table
type User struct {
    gorm.Model
    Languages         []Language `gorm:"many2many:user_languages;"`
}

type Language struct {
    gorm.Model
    Name string
}

db.Model(&user).Related(&languages)

Let's say I create a user and it has two associated languages.

I fetch a user record from the database and remove one language from the user's Languages array. I then save the user with gorm:save_associations set to true.

I would expect GORM to delete the record associating the user to this language (in the association table that GORM manages). However, it is not deleted. Is this expected?

Is it possible to delete many2many association records by removing a language from the Languages list on the user record and then saving the user? If not, how should this be done in GORM?

Update

I found a solution to this question, but not sure it's the best way to do this. I store the current languages, clear all the associations, then add back the languages, then save.

languages := user.Languages
DB.Model(&user).Association("Languages").Clear()
user.Languages = languages

Upvotes: 17

Views: 19660

Answers (4)

Purvesh
Purvesh

Reputation: 646

This is something that i am using it. If this is helpful to anyone.

db.Preload("Languages").Find(&user, r.FormValues("id"))

db.Model(&user).Association("Languages").Clear()
db.Save(&user) // We are deleting all the records first 

.....
.....
user.Languages = languages 
db.Save(&user) // Re insert all the records

Upvotes: 1

user3389
user3389

Reputation: 489

Also, you can do this by using "replace"

DB.Model(&user).Association("Languages").Replace(user.Languages)

Upvotes: 5

Alejandro Rangel
Alejandro Rangel

Reputation: 1670

I was having the same problem, If you want to just remove one of the associations this worked for me

    c.DB.Model(&user).Association("Roles").Delete(&role)

Upvotes: 12

Matthew S
Matthew S

Reputation: 1040

I found a solution to this question, but not sure it's the best way to do this. I store the current languages, clear all the associations, then add back the languages, then save.

languages := user.Languages 
DB.Model(&user).Association("Languages").Clear()
user.Languages = languages

Upvotes: 6

Related Questions