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.
The type of hook methods should be func(*gorm.DB) error
Hooks
Creating an object
Available hooks for creating
// begin transaction |
Code Example:
func (u *User) BeforeCreate(tx *gorm.DB) (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 committed, if you return any error in your hooks, the change will be rollbacked
func (u *User) AfterCreate(tx *gorm.DB) (err error) { |
Updating an object
Available hooks for updating
// begin transaction |
Code Example:
func (u *User) BeforeUpdate(tx *gorm.DB) (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(tx *gorm.DB) (err error) { |
Modify current operation
func (u *User) BeforeCreate(tx *gorm.DB) error { |