Gorm: Auto deletion on One-To-Many update

Created on 4 Mar 2015  路  7Comments  路  Source: go-gorm/gorm

I'm not sure if this behavior is intended or not.
Lets say we have User who has many Emails, then on retrieving a user, removing one of his emails, and saving him back, I expected to have that deleted email removed from database as well, which did not.

Most helpful comment

@jinzhu Would you accept a PR for a simular replace function for one-to-many?

All 7 comments

You need to do it like this:

db.Model(&user).Association("Languages").Replace([]Language{languageZH, languageEN})
db.Model(&user).Association("Languages").Replace(Language{Name: "DE"}, languageEN)

refer: https://github.com/jinzhu/gorm#many-to-many

It only works on many-to-many relations.

In other case, you should just delete the Email?

I can do that, but i was hoping for a more idiomatic way. With your suggestion, I should check related emails, to see if any item was deleted, then delete that email myself.

Is this dangerous? if you save the profile without any emails (because you haven't load emails into that profile), then I need to clear all emails for that profile?

So just delete it when you means that.

@jinzhu it would really be nice if you can provide similar mechanism ( as of many2many relation ) for handling related entity in one2many relation as well.

@jinzhu Would you accept a PR for a simular replace function for one-to-many?

Was this page helpful?
0 / 5 - 0 ratings