如何解决更新模型对象时如何将整数列设置为null?
假设我有如下模型类
type Catalog struct {
Title string `gorm:"column:title" json:"title"`
Description string `gorm:"column:description" json:"description"`
FeaturedMediumID uint `gorm:"column:featured_medium_id" json:"featured_medium_id" sql:"DEFAULT:NULL"`
FeaturedMedium *Medium `gorm:"foreignkey:featured_medium_id;association_foreignkey:id" json:"featured_medium"`
PublishedDate time.Time `gorm:"column:published_date" json:"published_date"`
Products []Product `gorm:"many2many:catalog_product;" json:"products"`
}
现在,当我在发布时创建对象时,如果我在请求正文中传递0,则FeaturedMediumID的值在数据库中设置为NULL。但是在那之后,如果我将其更新为某个值,然后再次想要取消设置该值,那将是不允许的。
我可以通过以下查询将其设置为NULL
DB.Model(catalog).Updates(map[string]interface{}{"featured_medium_id": nil}).First(&catalog).Error
但是我想直接在.Updates()
查询中进行操作。有什么办法吗?如果将其设置为0,将无法正常工作。
解决方法
组.Updates()
不更新类型(Ref)的零值
// WARNING when update with struct,GORM will only update those fields that with non blank value
// For below Update,nothing will be updated as "",false are blank values of their types
db.Model(&user).Updates(User{Name: "",Age: 0,Actived: false})
uint
的零值为0
,但对于uint
的指针,nil
不会忽略0
作为空白值。您需要使用uint
的指针,然后如果您发送FeaturedMediumID
,0
将在数据库中更新为0
。
type Catalog struct {
...
FeaturedMediumID *uint `gorm:"column:featured_medium_id" json:"featured_medium_id" sql:"DEFAULT:NULL"`
...
}
,
您必须使用null package
。
例如:
type Catalog struct {
Title string `gorm:"column:title" json:"title"`
Description string `gorm:"column:description" json:"description"`
FeaturedMediumID null.Int `gorm:"column:featured_medium_id" json:"featured_medium_id" sql:"DEFAULT:NULL"`
FeaturedMedium *Medium `gorm:"foreignkey:featured_medium_id;association_foreignkey:id" json:"featured_medium"`
PublishedDate time.Time `gorm:"column:published_date" json:"published_date"`
Products []Product `gorm:"many2many:catalog_product;" json:"products"`
}
然后将其设置为null,您必须执行以下操作:
null.IntFromPtr(nil)
必须从代码中执行以下操作:
yourStruct := Catalog{}
yourStruct.FeaturedMediumID = null.IntFromPtr(nil)
然后您可以使用update
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。