GORM Playground Link
https://github.com/go-gorm/playground/pull/521
Description
This is a bit of an edge case I found: BeforeSave prevents legitimate updates when objects aren't loaded in memory (that's my theory at least, based on the repro test cases).
Solving this one is tricky: to fully evaluate BeforeSave hooks upon Update and guarantee correctness, gorm would have to load the affected records from the DB to run the hook(s) over them; then do the update.
Another acceptable solution could be to prevent these types of updates entirely when hooks are defined, to minimize surprising behavior. I'm thinking about an error message along the lines of:
cannot update object without loading it in memory because the following hooks are defined: [BeforeSave, BeforeUpdate]. Please load records before updating them.
Comment From: howiieyu
I got some similar problem. It looks like that if Model(model) is called, GORM will call hook by model.hook(gorm).
In your case, it will call &company{}.BeforeSave(db), undoubtedly company.Name is empty, so update failed.
Comment From: peterdeme
@howiieyu same issue here. This is why:
https://github.com/go-gorm/gorm/blob/04cbd956ebed5fec1b61a819a3f7494c00d276b3/callbacks/update.go#L36-#L41
I could only work around with it with:
db.Session(&gorm.Session{SkipHooks: true}).Model(&Model{}).Where("id = ?", model.ID).Update("column", "value")
Comment From: a631807682
As the above comment said, some users may ask, it seems that we know the dbname, so why don't we assign it back? Because Update is mainly used to update one column, and the updated value may also be an expression.
https://gorm.io/docs/update.html#Update-with-SQL-Expression similar to https://github.com/go-gorm/gorm/issues/6110