我在 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 以取消引用。
如何更新这样的完整模型?
呼如林
相关分类