func (con BankController) Index(c *gin.Context) {
tx := models.DB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
con.error(c)
}
}()
u1 := models.Bank{Id: 1}
tx.Find(&u1)
u1.Balance = u1.Balance - 100
if err := tx.Save(&u1).Error; err != nil {
tx.Rollback()
con.error(c)
return
}
u2 := models.Bank{Id: 2}
tx.Find(&u2)
u2.Balance = u2.Balance + 100
if err := tx.Save(&u2).Error; err != nil {
tx.Rollback()
con.error(c)
return
}
tx.Commit()
con.success(c)
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
参考文档:https://gorm.io/zh_CN/docs/transactions.html