Reputation: 33
I followed the document code same struct and migrate
here's my model
type User struct {
gorm.Model
AddressID uint ``
Address UserAddress `gorm:"references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
}
type UserAddress struct {
gorm.Model
Address string `gorm:"type:varchar(50);notNull"`
}
document works fine when migrate and create data
db.AutoMigrate(&UserAddress{})
db.AutoMigrate(&User{})
but when I try update data use associations
user := &User{
ID: 1,
AddressID: 1,
Address: UserAddress{
Address: "new address",
},
}
db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user)
document says:
If you want to update associations’s data, you should use the FullSaveAssociations mode:
then it still create a new data of address and update user.address_id
INSERT INTO `user_address` (`address`,`created_at`,`updated_at`,`deleted_at`) VALUES ('changed','2021-08-13 14:07:39.149','2021-08-13 14:07:39.149',NULL) ON DUPLICATE KEY UPDATE `address`=VALUES(`address`),`created_at`=VALUES(`created_at`),`updated_at`=VALUES(`updated_at`),`deleted_at`=VALUES(`deleted_at`)
where am I missing here or it just doesn't work at all?
Upvotes: 0
Views: 1263
Reputation: 636
You didn't give a unique id for Address. So it create new address record with autoincrement ID. And update the ID value associated with it.
user := &User{
ID: 1,
AddressID: 1,
Address: UserAddress{
ID: 1,
Address: "new address",
},
}
Upvotes: 2