2 回答

TA贡献1868条经验 获得超4个赞
您可以使用scope.SetColumn在BeforeCreate钩子中设置字段的值
func (a *Address) BeforeCreate(scope *gorm.Scope) error {
scope.SetColumn("ID", uuid.New())
return nil
}
参考:https ://v1.gorm.io/docs/create.html#Setting-Field-Values-In-Hooks

TA贡献1794条经验 获得超8个赞
您应该使用tx.Statement.SetColumn在 GORM 挂钩中设置字段值,例如BeforeCreate. 以下是示例实现。
func (s Product3) BeforeCreate(tx *gorm.DB) (err error) {
tx.Statement.SetColumn("Price", s.Price+100)
return nil
}
GORM Github repo 的参考实现链接 https://github.com/go-gorm/gorm/blob/ac722c16f90e0e0dffc600c7f69e791c110d788c/tests/hooks_test.go#L306-L309
来自 GORM 文档的参考链接 https://gorm.io/docs/update.html#Change-Updating-Values
- 2 回答
- 0 关注
- 435 浏览
添加回答
举报