1. Callbacks
您可以將回調方法定義為模型結構的指針,在創建,更新,查詢,刪除時將被調用,如果任何回調返回錯誤,gorm將停止未來操作並回滾所有更改。
1.1. 創建對象
創建過程中可用的回調
// begin transaction 開始事物
BeforeSave
BeforeCreate
// save before associations 保存前關聯
// update timestamp `CreatedAt`, `UpdatedAt` 更新`CreatedAt`, `UpdatedAt`時間戳
// save self 保存自己
// reload fields that have default value and its value is blank 重新加載具有默認值且其值為空的字段
// save after associations 保存后關聯
AfterCreate
AfterSave
// commit or rollback transaction 提交或回滾事務
1.2. 更新對象
更新過程中可用的回調
// begin transaction 開始事物
BeforeSave
BeforeUpdate
// save before associations 保存前關聯
// update timestamp `UpdatedAt` 更新`UpdatedAt`時間戳
// save self 保存自己
// save after associations 保存后關聯
AfterUpdate
AfterSave
// commit or rollback transaction 提交或回滾事務
1.3. 刪除對象
刪除過程中可用的回調
// begin transaction 開始事物
BeforeDelete
// delete self 刪除自己
AfterDelete
// commit or rollback transaction 提交或回滾事務
1.4. 查詢對象
查詢過程中可用的回調
// load data from database 從數據庫加載數據
// Preloading (edger loading) 預加載(加載)
AfterFind
1.5. 回調示例
func (u *User) BeforeUpdate() (err error) {
if u.readonly() {
err = errors.New("read only user")
}
return
}
// 如果用戶ID大於1000,則回滾插入
func (u *User) AfterCreate() (err error) {
if (u.Id > 1000) {
err = errors.New("user id is already greater than 1000")
}
return
}
gorm中的保存/刪除操作正在事務中運行,因此在該事務中所做的更改不可見,除非提交。 如果要在回調中使用這些更改,則需要在同一事務中運行SQL。 所以你需要傳遞當前事務到回調,像這樣:
func (u *User) AfterCreate(tx *gorm.DB) (err error) {
tx.Model(u).Update("role", "admin")
return
}
func (u *User) AfterCreate(scope *gorm.Scope) (err error) {
scope.DB().Model(u).Update("role", "admin")
return
}