mirror of https://github.com/go-gorm/gorm.git
Update README with clear explanation of transaction db handle
This commit is contained in:
parent
64f61aaaf9
commit
ded91a21fe
15
README.md
15
README.md
|
@ -855,23 +855,26 @@ db.Joins("left join users on users.id = emails.user_id").Where("users.name = ?",
|
||||||
|
|
||||||
## Transactions
|
## Transactions
|
||||||
|
|
||||||
All individual save and delete operations are run in a transaction by default.
|
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
|
||||||
tx := db.Begin()
|
tx := db.Begin()
|
||||||
|
|
||||||
// do revertable work in a transaction (use 'tx' in place of 'db')
|
// do some database operations (use 'tx' from this point, not 'db')
|
||||||
tx.Exec
|
tx.Create(...)
|
||||||
|
...
|
||||||
|
|
||||||
// rollback
|
// rollback in case of error
|
||||||
tx.Rollback()
|
tx.Rollback()
|
||||||
|
|
||||||
// commit
|
// Or commit if all is ok
|
||||||
tx.Commit()
|
tx.Commit()
|
||||||
```
|
```
|
||||||
|
|
||||||
### More Complex Example
|
### A Specific Example
|
||||||
```
|
```
|
||||||
func CreateAnimals(db *gorm.DB) err {
|
func CreateAnimals(db *gorm.DB) err {
|
||||||
tx := db.Begin()
|
tx := db.Begin()
|
||||||
|
|
Loading…
Reference in New Issue