網站首頁 編程語言 正文
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 }
原文鏈接:https://www.cnblogs.com/guyouyin123/p/14115408.html
相關推薦
- 2022-09-20 linux?shell字符串截取的詳細總結(實用!)_linux shell
- 2022-08-04 淺析.net?core?拋異常對性能影響_實用技巧
- 2023-01-18 pip?search報錯問題及解決_python
- 2022-08-01 Python3?中return和yield的區別_python
- 2023-03-05 so加載Linker跟NameSpace機制詳解_Android
- 2022-07-06 windows清理系統垃圾bat腳本及使用步驟_DOS/BAT
- 2022-09-22 vrrp協議與keepalived淺析
- 2022-10-31 Kotlin類與屬性及構造函數的使用詳解_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支