Gorm不更新子结构体数组。

huangapple go评论112阅读模式
英文:

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)

See: https://gorm.io/docs/associations.html

huangapple
  • 本文由 发表于 2022年8月4日 20:09:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/73235724.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定