Your Question
type User struct {
Name string
}
func (u *User) BeforeUpdate(*gorm.DB) error {
u.Name = "Faker"
return nil
}
db.Debug().Model(&model.User{}).Where("name = ?", "Chovy").Update("name", "ShowMaker")
// [0.583ms] [rows:1] UPDATE `users` SET `name`='ShowMaker' WHERE name = 'Chovy'
The document you expected this should be explained
https://gorm.io/zh_CN/docs/hooks.html#%E6%9B%B4%E6%96%B0%E5%AF%B9%E8%B1%A1
Expected answer
为什么BeforeUpdate中对User.Name的设置不生效?
Comment From: a631807682
At this time, user refers to &model.User{}, which has nothing to do with updating. If you want to specify the value of a field, you can use SetColumn
func (u *User) BeforeUpdate(tx *gorm.DB) error {
tx.Statement.SetColumn("name", "Faker")
return nil
}