1. Callbacks
You can define the callback method as a pointer to the model structure, which will be called when created, updated, queryed, deleted, and if any callback returns an error, gorm will stop future operations and roll back all changes.
1.1. Create an object
Callbacks available during creation
// begin transaction starts transactionBeforeSave BeforeCreate // save before associations// update timestamp `CreatedAt`, `UpdatedAt` timestamp// save yourself// reload fields that have default value and its value is blank Reload fields that have default value and its value is blank// save after associationsAfterCreate AfterSave // commit or rollback transaction commit or rollback transaction
1.2. Update the object
Callbacks available during the update process
// begin transaction starts transactionBeforeSave BeforeUpdate // save before associations// update timestamp `UpdatedAt` timestamp// save yourself// save after associationsAfterUpdate AfterSave // commit or rollback transaction commit or rollback transaction
1.3. Delete Objects
Callbacks available during the deletion process
// begin transaction starts transactionBeforeDelete // delete selfAfterDelete // commit or rollback transaction commit or rollback transaction
1.4. Query Objects
Callbacks available during query
// load data from database load data from database// Preloading (edger loading) Preloading (loading)AfterFind
1.5. Callback example
func (u *User) BeforeUpdate() (err error) { if () { err = ("read only user") } return } // If the user ID is greater than 1000, rollback insertfunc (u *User) AfterCreate() (err error) { if ( > 1000) { err = ("user id is already greater than 1000") } return }
The save/delete operation in gorm is running in a transaction, so the changes made in that transaction are not visible unless committed.
If you want to use these changes in the callback, you need to run SQL in the same transaction.
So you need to pass the current transaction to the callback, like this:
func (u *User) AfterCreate(tx *) (err error) { (u).Update("role", "admin") return } func (u *User) AfterCreate(scope *) (err error) { ().Model(u).Update("role", "admin") return }
The above is the detailed content of the callbacks transaction rollback object operation example of golang gorm. For more information about golang gorm's Callbacks transaction rollback, please follow my other related articles!