Update advanced document

This commit is contained in:
Jinzhu 2016-03-08 09:58:31 +08:00
parent 0a92f14d87
commit 187b23c091

View File

@ -4,45 +4,41 @@
## Error Handling ## Error Handling
```go After perform any operations, if there are any error happened, GORM will set it to `*DB`'s `Error` field
query := db.Where("name = ?", "jinzhu").First(&user)
query := db.First(&user).Limit(10).Find(&users)
// query.Error will return the last happened error
// So you could do error handing in your application like this: ```go
if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil { if err := db.Where("name = ?", "jinzhu").First(&user).Error; err != nil {
// error handling... // error handling...
} }
// RecordNotFound // If there are more than one error happened, get all of them with `GetErrors`, it returns `[]error`
// If no record found when you query data, gorm will return RecordNotFound error, you could check it like this: db.First(&user).Limit(10).Find(&users).GetErrors()
db.Where("name = ?", "hello world").First(&User{}).Error == gorm.RecordNotFound
// Or use the shortcut method // Check if returns RecordNotFound error
db.Where("name = ?", "hello world").First(&user).RecordNotFound() db.Where("name = ?", "hello world").First(&user).RecordNotFound()
if db.Model(&user).Related(&credit_card).RecordNotFound() { if db.Model(&user).Related(&credit_card).RecordNotFound() {
// no credit card found error handling // no credit card found handling
} }
``` ```
## Transactions ## Transactions
To perform a set of operations within a transaction, the general flow is as below. To perform a set of operations within a transaction, the general flow is as below.
The database handle returned from ``` db.Begin() ``` should be used for all operations within the transaction.
(Note that all individual save and delete operations are run in a transaction by default.)
```go ```go
// begin // begin a transaction
tx := db.Begin() tx := db.Begin()
// do some database operations (use 'tx' from this point, not 'db') // do some database operations in the transaction (use 'tx' from this point, not 'db')
tx.Create(...) tx.Create(...)
...
// rollback in case of error // ...
// rollback the transaction in case of error
tx.Rollback() tx.Rollback()
// Or commit if all is ok // Or commit the transaction
tx.Commit() tx.Commit()
``` ```