GORM Playground Link
https://github.com/go-gorm/playground/pull/662
Description
After adding BeforeSave
hook, updating model with TableName and struct will get error. It seems too incredible😂
Comment From: ivila
I think this is mainly because of the conflict between schema analyzer and the update callbacks. Where you call Updates by passing a struct
err := DB.Table(User{}.TableName()).Where("name = ?", "jinzhu").Updates(User{Name: "foo"}).Error
if err != nil {
panic(err)
}
gorm auto set the target model by the argument of the Updates method, see here https://github.com/go-gorm/gorm/blob/3207ad6033aad5e76c6c9d578ef663032765e484/finisher_api.go#L406. and then it analyzes the schema of the dest, as we can see here: https://github.com/go-gorm/gorm/blob/3207ad6033aad5e76c6c9d578ef663032765e484/schema/schema.go#L164, it calls a reflect.New method to get a pointer to the struct(aka *User), which result in it thinks the Target has BeforeSave implementation, check here https://github.com/go-gorm/gorm/blob/3207ad6033aad5e76c6c9d578ef663032765e484/schema/schema.go#L305. finally when the callbacks chain executing, the BeforeUpdate hook thinks it should be executed(check here https://github.com/go-gorm/gorm/blob/3207ad6033aad5e76c6c9d578ef663032765e484/callbacks/update.go#L34), however, the argument is a struct, so it doesn't due to the value is actually a struct and didn't imply a BeforeSave(check here https://github.com/go-gorm/gorm/blob/3207ad6033aad5e76c6c9d578ef663032765e484/callbacks/update.go#L37), which result in the error(check here https://github.com/go-gorm/gorm/blob/3207ad6033aad5e76c6c9d578ef663032765e484/callbacks/callmethod.go#L28)
Comment From: maasg
I'm observing the same error when passing a map
. Is there any workaround available?
Comment From: radoen-psi
I got the same issue use a DB.WithContext(ctx).Model(entity.MyEntity{}), how can we solve it?
Comment From: 0b010
I got the same issue use a DB.WithContext(ctx).Model(entity.MyEntity{}), how can we solve it?
try ### DB.WithContext(ctx).Model(&entity.MyEntity{})