猿问

GORM 中的复杂更新

我在 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 以取消引用。


如何更新这样的完整模型?


慕雪6442864
浏览 283回答 1
1回答

呼如林

要更新现有数据,您可以获取第一个预加载子var country Countrydb.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).ErrorReplace 仅将关联方式替换为其他。如果您不提供任何信息,它只会删除与Country此处的当前关联。只是Regions它不是儿童城市。Gorm 不支持更新时的任何删除操作。它仅用于添加或更新现有数据。Gorm 模型默认使用软删除。如果您以这种方式删除区域,它将更新deleted_at字段数据。并且在查询时它总是过滤掉已删除的数据。db.Delete(county.Regions)而且它不会软删除 City,你必须这样做。db.Delete(region.Cities)这里有一个工作代码示例
随时随地看视频慕课网APP

相关分类

Go
我要回答