作为一个简单的背景,我有一个表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 版本也没有错误
。
我尝试将 Foo.BarId 的类型更改为 *int64
,并将指针设置为 nil
,但输出查询没有更改 bar_id
为 NULL。
我需要做什么?
最佳答案
我明白了。我需要在 Select()
中专门包含该列:
db.Model(&foo).Select("bar_id").Updates(map[string]interface{}{"bar_id": nil})
关于Gorm : How do I set an integer column to null, 并更新内存中的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54698391/