From 0a92f14d8741a413a02bfc8545c079a83855aa00 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Tue, 8 Mar 2016 09:50:42 +0800 Subject: [PATCH] Update callback document --- documents/callbacks.md | 44 ++++++++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 12 deletions(-) diff --git a/documents/callbacks.md b/documents/callbacks.md index 18ef4cca..86cae71b 100644 --- a/documents/callbacks.md +++ b/documents/callbacks.md @@ -2,51 +2,66 @@ -Callbacks are methods defined on the pointer of struct. -If any callback returns an error, gorm will stop future operations and rollback all changes. - -Here is the list of all available callbacks: -(listed in the same order in which they will get called during the respective operations) +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 + ```go +// begin transaction BeforeSave BeforeCreate // save before associations +// update timestamp `CreatedAt`, `UpdatedAt` // save self +// reload fields that have default value and its value is blank // save after associations AfterCreate AfterSave +// commit or rollback transaction ``` + ### Updating An Object +Available Callbacks for updating + ```go +// begin transaction BeforeSave BeforeUpdate // save before associations +// update timestamp `UpdatedAt` // save self // save after associations AfterUpdate AfterSave +// commit or rollback transaction ``` -### Destroying An Object +### Deleting An Object + +Available Callbacks for deleting ```go +// begin transaction BeforeDelete // delete self AfterDelete +// commit or rollback transaction ``` -### After Find +### Querying An Object + +Available Callbacks for querying ```go // load data from database +// Preloading (edger loading) AfterFind ``` -### Example +### Callback Examples ```go func (u *User) BeforeUpdate() (err error) { @@ -65,10 +80,8 @@ func (u *User) AfterCreate() (err error) { } ``` -Save/delete operations in gorm are running in a transaction. -Changes made in that transaction are not visible unless it is commited. -So if you want to use those changes in your callbacks, you need to run your SQL in the same transaction. -For this Gorm supports passing transactions to callbacks like this: +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: ```go func (u *User) AfterCreate(tx *gorm.DB) (err error) { @@ -76,3 +89,10 @@ func (u *User) AfterCreate(tx *gorm.DB) (err error) { return } ``` + +```go +func (u *User) AfterCreate(scope *gorm.Scope) (err error) { + scope.DB().Model(u).Update("role", "admin") + return +} +```