dongqixuan3112 2019-02-14 20:15
浏览 1245
已采纳

Gorm:如何将整数列设置为null,并更新内存中的模型?

As a simple background, I have a table foo, with a nullable int foreign key bar_id. I have a function that removes the bar association from foo, aka set it to NULL.

I have tried everything: I tried using sql.NullInt64 as the column type, and then

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

bar_id was not updated in the UPDATE statement

I tried:

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

The SQL was correct thankfully, but the object is not updated. I don't think my version of gorm has Error either.

I tried changing the type of Foo.BarId to an *int64, and setting the pointer to nil, but the output query didn't change bar_id to NULL.

What do I need to do?

  • 写回答

1条回答 默认 最新

  • dongya9904 2019-02-14 21:19
    关注

    I got it. I need to specifically include the column in a Select():

    db.Model(&foo).Select("bar_id").Updates(map[string]interface{}{"bar_id": nil})
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?