Is there a way to replace associations without making a call to insert the associated entities?
The document you expected this should be explained
https://gorm.io/docs/associations.html#Replace-Associations
Expected answer
Entity create/update operations have the option to skip auto create/update, and I was wondering if there was a way to do this for replacing associations. Similar to
db.Omit("Languages.*").Create(&user)
I'd like to be able to call something like
db.Model(&user).Association("Languages").Omit("Languages.*").Replace([]Language{languageZH, languageEN})
so that INSERT INTO "languages"... is not called.
Currently I see
1. INSERT INTO "languages" (...) VALUES (...) ON CONFLICT DO NOTHING
2. INSERT INTO "user_languages" ("user_id","language_id") VALUES (...) ON CONFLICT DO NOTHING
3. DELETE from "user_languages" WHERE "user_id" = $1 AND "language_id" NOT IN (...)
Ideally I would like to see only steps 2 and 3.
Comment From: knlambert
Maybe I'm missing something, I don't use this lib a lot, but I have trouble to understand why the version 2 of GORM always try to insert stuffs with associations (I don't think it was doing that in the v1).
If I take this example which is very similar to my use cases, most of the time the items from the language table are created in a separate process, so I don't need to add them again each time I create a user :(
Comment From: charlieparkes
Is there really no way to do this atm? I'm trying to avoid creating a many2many table manually and inserting those rows myself, but I feel like I'll have to if there's no way to "Omit" inserts when doing Append and Replace.
Comment From: jinzhu
Already supported in latest release.
Comment From: jinzhu
use it like:
db.Model(&user).Omit("Languages.*").Association("Languages").Append(&langs)
Comment From: inliquid
Thanks!