英文:
why create a new row when gorm update associations
问题
我按照文档中的代码结构进行了迁移,这是我的模型:
type User struct {
gorm.Model
AddressID uint `gorm:""`
Address UserAddress `gorm:"references:ID;constraint:OnUpdate:CASCADE,OnDelete:SET NULL"`
}
type UserAddress struct {
gorm.Model
Address string `gorm:"type:varchar(50);notNull"`
}
当我迁移并创建数据时,文档中的代码可以正常工作:
db.AutoMigrate(&UserAddress{})
db.AutoMigrate(&User{})
但是,当我尝试使用关联更新数据时,出现了问题:
user := &User{
ID: 1,
AddressID: 1,
Address: UserAddress{
Address: "new address",
},
}
db.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&user)
文档中说:
如果你想更新关联数据,你应该使用 FullSaveAssociations 模式:
然而,它仍然会创建一个新的地址数据并更新 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`)
我在哪里出错了?或者它根本不起作用?
英文:
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?
答案1
得分: 1
你没有为地址(Address)提供唯一的ID,所以它会创建一个新的地址记录,并自动递增ID。然后更新与之关联的ID值。
user := &User{
ID: 1,
AddressID: 1,
Address: UserAddress{
ID: 1,
Address: "新地址",
},
}
英文:
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",
},
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论