Member-only story

Cannot update zero value with Gorm

Recently I met an issue which I cannot update postgresql boolean field with gorm to false.

Donald Le
Aug 27, 2021
Photo by Rizky Subagja on Unsplash

Turns out, Gorm will only update non-zero value. Checkout their documentation in here.

Updates supports update with struct or map[string]interface{}, when updating with struct it will only update non-zero fields by default// Update attributes with `struct`, will only update non-zero fields
db.Model(&user).Updates(User{Name: "hello", Age: 18, Active: false})
// UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;

// Update attributes with `map`
db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false})
// UPDATE users SET name='hello', age=18, active=false, updated_at='2013-11-17 21:34:10' WHERE id=111;

NOTE When update with struct, GORM will only update non-zero fields, you might want to use map to update attributes or use Select to specify fields to update

Hope it helps

~~PEACE~~

--

--

Donald Le
Donald Le

Written by Donald Le

A passionate automation engineer who strongly believes in “A man can do anything he wants if he puts in the work”.

No responses yet