更新模型对象时如何将整数列设置为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的指针,然后如果您发送FeaturedMediumID0将在数据库中更新为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