Describe the feature
It would be very useful to be able to update bool values (even when they are the zero value false) using the form of Update() in which the struct is passed in. For example:
db.Model(&some_struct).Updates(&some_struct)
A gorm configuration option would be useful that specified that bool values specifically should always be updated regardless of whether it is the zero value or not.
(I know the current behavior is documented in Updates multiple columns. I'm asking for a way to override that behavior for bool fields.)
Motivation
This would be very convenient for 2 reasons:
- Unlike the rest of the golang types, with
boolvalues the zero-value (false) is 1 of the "valid" values. So changing aboolfield fromtruetofalseis a common need. - The
structform ofUpdates()is very convenient because it enables its use in utility packages in which the code doesn't readily know the exact struct type being updated.
Related Issues
None
Comment From: a631807682
Why are bool type special, and in fact the zero value of int when you really need to update it.
1. If you need to update zero value, does Select("*").Update meet your needs?
https://gorm.io/docs/update.html#Update-Selected-Fields
2. If you really only need to update bool type zero value, you can use BeforeUpdate to change Statement Select/Omit .
You can also register all model hooks by Reflect.
https://gorm.io/docs/update.html#Update-Hooks
func (u *User) BeforeUpdate(tx *gorm.DB) (err error) {
tx.Statement.Select("*")
if u.OtherZeroValue == 0 {
tx.Statement.Omit("OtherZeroValue")
}
return
}
Comment From: a631807682
It seems that this update zero value field is rarely encountered, but it is very cumbersome every time.
I not sure it needs to be added to gorm, so i create a plugin to support it.
https://github.com/a631807682/zerofield
Comment From: bmpotter
@a631807682 Thanks for the suggestions! I will try them out.
Comment From: bmpotter
@a631807682 Just following up: your first suggestion above did exactly what we want. Thx!!
Comment From: hanayashiki
can't believe we talking about this in 21st century