Callbacks

You could define callback methods to pointer of model struct, it will be called when creating, updating, querying, deleting, if any callback returns an error, gorm will stop future operations and rollback all changes.

Creating An Object

Available Callbacks for creating

  1. // begin transaction
  2. BeforeSave
  3. BeforeCreate
  4. // save before associations
  5. // update timestamp `CreatedAt`, `UpdatedAt`
  6. // save self
  7. // reload fields that have default value and its value is blank
  8. // save after associations
  9. AfterCreate
  10. AfterSave
  11. // commit or rollback transaction

Updating An Object

Available Callbacks for updating

  1. // begin transaction
  2. BeforeSave
  3. BeforeUpdate
  4. // save before associations
  5. // update timestamp `UpdatedAt`
  6. // save self
  7. // save after associations
  8. AfterUpdate
  9. AfterSave
  10. // commit or rollback transaction

Deleting An Object

Available Callbacks for deleting

  1. // begin transaction
  2. BeforeDelete
  3. // delete self
  4. AfterDelete
  5. // commit or rollback transaction

Querying An Object

Available Callbacks for querying

  1. // load data from database
  2. // Preloading (edger loading)
  3. AfterFind

Callback Examples

  1. func (u *User) BeforeUpdate() (err error) {
  2. if u.readonly() {
  3. err = errors.New("read only user")
  4. }
  5. return
  6. }
  7. // Rollback the insertion if user's id greater than 1000
  8. func (u *User) AfterCreate() (err error) {
  9. if (u.Id > 1000) {
  10. err = errors.New("user id is already greater than 1000")
  11. }
  12. return
  13. }

Save/Delete operations in gorm are running in transactions, so changes made in that transaction are not visible unless it is commited.
If you want to use those changes in your callbacks, you need to run your SQL in the same transaction. So you need to pass current transaction to callbacks like this:

  1. func (u *User) AfterCreate(tx *gorm.DB) (err error) {
  2. tx.Model(u).Update("role", "admin")
  3. return
  4. }
  1. func (u *User) AfterCreate(scope *gorm.Scope) (err error) {
  2. scope.DB().Model(u).Update("role", "admin")
  3. return
  4. }