英文:
Gorm not updating array of child struct
问题
我有以下的结构体:
type Parent struct {
ID uuid `gorm:"type:uuid" example:"070942aa-604f-42d2-bc6f-7295eae1929d"`
Name string
Children []*Child `gorm:"constraint:OnUpdate:CASCADE"`
}
type Child struct {
ID uuid `gorm:"type:uuid" example:"070942aa-604f-42d2-bc6f-7295eae1929d"`
Age int
}
我想通过更新子项的信息来更新父实体。例如,通过保存/更新父实体来更新子项的年龄。我使用以下代码:
gorm.Updates(&updatedParent)
其中&updatedParent
包含子项的更新信息。但是,我可以更新父字段(在这种情况下是Name),但是无法更新子实体(在这种情况下是age)。我做错了什么吗?我以为gorm:"constraint:OnUpdate:CASCADE"
应该足够了。
英文:
I have the following structs
type Parent struct {
ID uuid `gorm:"type:uuid" example:"070942aa-604f-42d2-bc6f-7295eae1929d"`
Name string
Children []*Child `gorm:"constraint:OnUpdate:CASCADE"`
}
type Child struct {
ID uuid `gorm:"type:uuid" example:"070942aa-604f-42d2-bc6f-7295eae1929d"`
Age int
}
and I want to update the parent entity, with updated information of the child/children. As an example, update the children ages through saving/updating the parent entity, I am using this :
gorm.Updates(&updatedParent)
With &updatedParent containing the updated information of the children.
But I can update the parent fields (in this case Name), but I can't update the child entities (in this case age). Am I doing something wrong? I thought this gorm:"constraint:OnUpdate:CASCADE" should be sufficient
答案1
得分: 3
如果你想更新关联数据,你必须明确指定如下:
DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&parent)
参考:https://gorm.io/docs/associations.html
英文:
If you want to update associations data, you have to specify this explicitly like:
DB.Session(&gorm.Session{FullSaveAssociations: true}).Updates(&parent)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论