GORM allows method chaining, so you can write code like this:
db.Where("name = ?", "jinzhu").Where("age = ?", 18).First(&user) |
There are three kinds of methods in GORM: Chain Method
, Finisher Method
, New Session Method
.
After a Chain method
, Finisher Method
, GORM returns an initialized *gorm.DB
instance, which is NOT safe to reuse anymore, or new generated SQL might be polluted by the previous conditions, for example:
queryDB := DB.Where("name = ?", "jinzhu") |
In order to reuse a initialized *gorm.DB
instance, you can use a New Session Method
to create a shareable *gorm.DB
, e.g:
queryDB := DB.Where("name = ?", "jinzhu").Session(&gorm.Session{}) |
Chain Method
Chain methods are methods to modify or add Clauses
to current Statement
, like:
Where
, Select
, Omit
, Joins
, Scopes
, Preload
, Raw
(Raw
can’t be used with other chainable methods to build SQL)…
Here is the full lists, also check out the SQL Builder for more details about Clauses
.
Finisher Method
Finishers are immediate methods that execute registered callbacks, which will generate and execute SQL, like those methods:
Create
, First
, Find
, Take
, Save
, Update
, Delete
, Scan
, Row
, Rows
…
Check out the full lists here.
New Session Method
GORM defined Session
, WithContext
, Debug
methods as New Session Method
, refer Session for more details.
After a Chain method
, Finisher Method
, GORM returns an initialized *gorm.DB
instance, which is NOT safe to reuse anymore, you should use a New Session Method
to mark the *gorm.DB
as shareable.
Let’s explain it with examples:
Example 1:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) |
(Bad) Example 2:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) |
Example 3:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) |