Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gorm: How do I set an integer column to null, and update the model in-memory?

Tags:

go

go-gorm

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?

like image 856
limasxgoesto0 Avatar asked Oct 20 '25 12:10

limasxgoesto0


2 Answers

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})
like image 171
limasxgoesto0 Avatar answered Oct 23 '25 07:10

limasxgoesto0


you can use gorm.Expr("NULL") also like below :

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

you can use this also on datetime database field type.

like image 25
Arian Saputra Avatar answered Oct 23 '25 09:10

Arian Saputra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!