【问题标题】:Gorm: How do I set an integer column to null, and update the model in-memory?Gorm:如何将整数列设置为空,并更新内存中的模型?
【发布时间】:2019-02-14 20:15:16
【问题描述】:

作为一个简单的背景,我有一个表foo,带有一个可为空的int 外键bar_id。我有一个函数可以从foo 中删除bar 关联,也就是将其设置为NULL

我已经尝试了一切:我尝试使用sql.NullInt64作为列类型,然后

foo.BarId.Valid = false // even set Int64 = 0 for good measure
db.Save(&foo) // with LogMode(true)

bar_id 未在 UPDATE 语句中更新

我试过了:

db.Raw("UPDATE foo SET bar_id = NULL WHERE id = ?", foo.ID).Row().Scan(&foo)

谢天谢地,SQL 是正确的,但对象没有更新。我认为我的 gorm 版本也没有 Error

我尝试将 Foo.BarId 的类型更改为 *int64,并将指针设置为 nil,但输出查询并未将 bar_id 更改为 NULL。

我需要做什么?

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    我明白了。我需要在Select() 中专门包含该列:

    db.Model(&foo).Select("bar_id").Updates(map[string]interface{}{"bar_id": nil})
    

    【讨论】:

      【解决方案2】:

      另一种方法:

      //RemoveAllChildren  remove all the children
       func RemoveAllChildren(db *gorm.DB, dataEdit Mat) (Mat, error) {
           var matupdate Mat
           db.Where("id = ?", dataEdit.ID).First(&matupdate)
           if err := db.Model(&matupdate).Update("children_mat", gorm.Expr("NULL")); err != nil {
                   return matupdate, errors.New("cannotUpdate")
           }
           return matupdate, nil
       }
      

      参考:https://gist.github.com/thanhtungka91/186dca4cd14d30581bb98193153a55bf

      【讨论】:

        【解决方案3】:

        您也可以使用gorm.Expr("NULL"),如下所示:

        db.Model(&foo).Select("bar_id").Updates(map[string]interface{}{"bar_id": gorm.Expr("NULL")})
        

        您也可以在 datetime 数据库字段类型上使用它。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-02-12
          • 2021-01-13
          • 2012-04-17
          • 2018-01-08
          • 2017-01-30
          • 1970-01-01
          • 2023-02-15
          相关资源
          最近更新 更多