Object Life Cycle
Hooks are functions that are called before or after creation/querying/updating/deletion.
If you have defined specified methods for a model, it will be called automatically when creating, updating, querying, deleting, and if any callback returns an error, GORM will stop future operations and rollback current transaction.
Hooks
Creating an object
Available hooks for creating
// begin transaction |
Code Example:
func (u *User) BeforeSave() (err error) { |
NOTE Save/Delete operations in GORM are running in transactions by default, so changes made in that transaction are not visible until it is commited.
If you would like access those changes in your hooks, you could accept current transaction as argument in your hooks, for example:
func (u *User) AfterCreate(tx *gorm.DB) (err error) { |
Updating an object
Available hooks for updating
// begin transaction |
Code Example:
func (u *User) BeforeUpdate() (err error) { |
Deleting an object
Available hooks for deleting
// begin transaction |
Code Example:
// Updating data in same transaction |
Querying an object
Available hooks for querying
// load data from database |
Code Example:
func (u *User) AfterFind() (err error) { |