为了账号安全,请及时绑定邮箱和手机立即绑定

GORM 中的复杂更新

GORM 中的复杂更新

Go
慕雪6442864 2022-06-06 17:55:47
我在 GORM 中有一个以 Postgres 作为数据库的模型。模型是这样的type Country struct {    gorm.Model    Name   string    Population int64    Regions []Region}type Region struct {    gorm.Model    Name   string    Cities []City    CountryID uint `sql:"type:bigint REFERENCES countries(id) ON DELETE CASCADE" json:"-"`}type City struct {    gorm.Model    Name        string    Comment string    RegionID   uint `sql:"type:bigint REFERENCES regions(id) ON DELETE CASCADE" json:"-"`}当我从模型创建新记录时,我调用 create 函数db.Create(&menu)现在,我正在尝试更新模型,但遇到了一些问题。如果我调用这个err = db.Debug().Where("id = ?", countryId).Updates(&country).Error我有一个错误,模型未在数据库中更新更新:错误是(C:/source/go/gorm/country.go:100) [2020-06-06 02:37:59]  sql: converting argument $4 type: unsupported type []main.Region, a slice of struct (C:/source/go/gorm/country.go:100) [2020-06-06 02:37:59]  [0.00ms]  UPDATE "" SET "created_at" = '2020-06-06 00:37:50', "id" = 1, "name" = 'New Name', "regions" = '[{{1 2020-06-06 00:37:50.450497 +0000 UTC 2020-06-06 00:37:50.450497 +0000 UTC <nil>} Region 1 [{{1 2020-06-06 00:37:50.465029 +0000 UTC 2020-06-06 00:37:50.465029 +0000 UTC <nil>} City 1  1}] 1} {{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} Region 2 updated [{{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>} City 2 updated  0}] 0}]', "updated_at" = '2020-06-06 00:37:50'  WHERE (id = 1)  [0 rows affected or returned ] 如果我跑err = db.Debug().Model(&country).Association("Regions").Replace(country.Regions).Error地区和城市模型在数据库中更新,但国家模型未更新。除此之外,对于更新删除元素期间的区域模型,CountryID 为 null,但城市模型不会更新其 RegionID 以取消引用。如何更新这样的完整模型?
查看完整描述

1 回答

?
呼如林

TA贡献1798条经验 获得超3个赞

要更新现有数据,您可以获取第一个预加载子


var country Country

db.Preload("Regions").Preload("Regions.Cities").First(&country, 1)

然后您可以更新数据并添加新数据,例如


country.Regions[0].Cities[0].Name = "Dhaka City 1"

country.Regions[0].Name = "Dhaka Region 1"

country.Regions[1].Cities = append(country.Regions[1].Cities, City{Name: "Dhaka City 2"})

现在将更新的数据保存在数据库中


db.Save(&country)

如果您只想添加新的子数据,您也可以避免 Preload。


db.First(&country, 8)

country.Regions = append(country.Regions, Region{Name: "Dhaka Region 3"})

db.Save(&country)

默认情况下,gormassociation_autoupdate标志设置为true,因此它是自动保存关联。


err = db.Debug().Model(&country).Association("Regions").Replace(country.Regions).Error

Replace 仅将关联方式替换为其他。如果您不提供任何信息,它只会删除与Country此处的当前关联。只是Regions它不是儿童城市。


Gorm 不支持更新时的任何删除操作。它仅用于添加或更新现有数据。Gorm 模型默认使用软删除。如果您以这种方式删除区域,它将更新deleted_at字段数据。并且在查询时它总是过滤掉已删除的数据。


db.Delete(county.Regions)

而且它不会软删除 City,你必须这样做。


db.Delete(region.Cities)

这里有一个工作代码示例


查看完整回答
反对 回复 2022-06-06
  • 1 回答
  • 0 关注
  • 282 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号