2 回答

TA貢獻(xiàn)1868條經(jīng)驗(yàn) 獲得超4個贊
您可以使用scope.SetColumn在BeforeCreate鉤子中設(shè)置字段的值
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貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個贊
您應(yīng)該使用tx.Statement.SetColumn在 GORM 掛鉤中設(shè)置字段值,例如BeforeCreate. 以下是示例實(shí)現(xiàn)。
func (s Product3) BeforeCreate(tx *gorm.DB) (err error) {
tx.Statement.SetColumn("Price", s.Price+100)
return nil
}
GORM Github repo 的參考實(shí)現(xiàn)鏈接 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 關(guān)注
- 433 瀏覽
添加回答
舉報