Auto Create/Update
GORM will auto save associations and its reference when creating/updating a record. if association has a primary key, GORM will call Update
to save it, otherwise it will be created.
user := User{ |
Skip AutoUpdate
If your association is already existing in database, you might not want to update it.
You could use DB setting, set gorm:association_autoupdate
to false
// Don't update associations having primary key, but will save reference |
or use GORM tags, gorm:"association_autoupdate:false"
type User struct { |
Skip AutoCreate
Even though you disabled AutoUpdating
, associations w/o primary key still have to be created and its reference will be saved.
To disable this, you could set DB setting gorm:association_autocreate
to false
// Don't create associations w/o primary key, WON'T save its reference |
or use GORM tags, gorm:"association_autocreate:false"
type User struct { |
Skip AutoCreate/Update
To disable both AutoCreate
and AutoUpdate
, you could use those two settings together
db.Set("gorm:association_autoupdate", false).Set("gorm:association_autocreate", false).Create(&user) |
Or use gorm:save_associations
db.Set("gorm:save_associations", false).Create(&user) |
Skip Save Reference
If you don’t even want to save association’s reference when updating/saving data, you could use below tricks
db.Set("gorm:association_save_reference", false).Save(&user) |
or use tag
type User struct { |
Association Mode
Association Mode contains some helper methods to handle relationship related things easily.
// Start Association Mode |
Find Associations
Find matched associations
db.Model(&user).Association("Languages").Find(&languages) |
Append Associations
Append new associations for many to many
, has many
, replace current associations for has one
, belongs to
db.Model(&user).Association("Languages").Append([]Language{languageZH, languageEN}) |
Replace Associations
Replace current associations with new ones
db.Model(&user).Association("Languages").Replace([]Language{languageZH, languageEN}) |
Delete Associations
Remove relationship between source & argument objects, only delete the reference, won’t delete those objects from DB.
db.Model(&user).Association("Languages").Delete([]Language{languageZH, languageEN}) |
Clear Associations
Remove reference between source & current associations, won’t delete those associations
db.Model(&user).Association("Languages").Clear() |
Count Associations
Return the count of current associations
db.Model(&user).Association("Languages").Count() |