美文网首页
gorm update 更新改变的字段里的小陷阱

gorm update 更新改变的字段里的小陷阱

作者: show16 | 来源:发表于2018-09-24 17:32 被阅读660次

现象

gorm里对字段的更新有以下几种形式:更新所有字段,只更新改变的字段,只更新选中的字段,只更新改变的字段没有回调......

项目中使用了只更新改变的字段(只更新值改变了的字段)。当我们要把值更新为0(int型)或空字符串时,会发现更新不起作用。

这里AlarmLevel字段数据库值是1,现在想把它更新为0,会发现无法成功。

//更新
func (this *Item) Update() error {
    this.AlarmLevel=0
    if err := core.KwsDb.Model(&this).Where("id = ? and status != ?", this.ID, dbstatus.DELETE).Updates(this).Error; err != nil {
        if err == gorm.ErrRecordNotFound {
            return nil
        }
        log.Error(err)
        return err
    }
    return nil
}


原因

只更新改变的字段里有一段警告:

// WARNING when update with struct, GORM will only update those fields that with non blank value
// For below Update, nothing will be updated as "", 0, false are blank values of their types

当用结构体更新的时候,当结构体的值是""或者0,false等,就什么也不会更新。

解决方法

如果你要更新的字段值是0,"",false等,你可以使用以下方法:
① 使用更新所有字段方法(save)
② 使用更新选中字段的方法
③ 使用sql语句方法
④ 你的答案......

相关文章

网友评论

      本文标题:gorm update 更新改变的字段里的小陷阱

      本文链接:https://www.haomeiwen.com/subject/lzqhoftx.html