// begin transaction BeforeSave BeforeCreate // save before associations // insert into database // save after associations AfterCreate AfterSave // commit or rollback transaction
// begin transaction BeforeSave BeforeUpdate // save before associations // update database // save after associations AfterUpdate AfterSave // commit or rollback transaction
代码示例
func(u *User) BeforeUpdate(tx *gorm.DB) (err error) { if u.readonly() { err = errors.New("read only user") } return }
// Updating data in same transaction func(u *User) AfterUpdate(tx *gorm.DB) (err error) { if u.Confirmed { tx.Model(&Address{}).Where("user_id = ?", u.ID).Update("verfied", true) } return }
删除对象
可用于删除的钩子
// begin transaction BeforeDelete // delete from database AfterDelete // commit or rollback transaction
代码示例
// Updating data in same transaction func(u *User) AfterDelete(tx *gorm.DB) (err error) { if u.Confirmed { tx.Model(&Address{}).Where("user_id = ?", u.ID).Update("invalid", false) } return }
查询对象
可用于查询的钩子
// load data from database // Preloading (eager loading) AfterFind
func(u *User) BeforeCreate(tx *gorm.DB) error { // Modify current operation through tx.Statement, e.g: tx.Statement.Select("Name", "Age") tx.Statement.AddClause(clause.OnConflict{DoNothing: true})
// tx is new session mode with the `NewDB` option // operations based on it will run inside same transaction but without any current conditions var role Role err := tx.First(&role, "name = ?", user.Role).Error // SELECT * FROM roles WHERE name = "admin" // ... return err }