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
Chain Method
Chain methods are methods to modify or add Clauses
to current Statement
, like:
Where
, Select
, Omit
, Joins
, Scopes
, Preload
, Raw
…
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 Mode
After new initialized *gorm.DB
or a New Session Method
, following methods call will create a new Statement
instance instead of using the current one
GROM defined Session
, WithContext
, Debug
methods as New Session Method
, refer Session for more details
Let explain it with examples:
Example 1:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) |
Example 2:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) |
NOTE In example 2, the first query affected the second generated SQL as GORM reused the
Statement
, this might cause unexpected issues, refer Goroutine Safety for how to avoid it
Method Chain Safety/Goroutine Safety
Methods will create new Statement
instances for new initialized *gorm.DB
or after a New Session Method
, so to reuse a *gorm.DB
, you need to make sure they are under New Session Mode
, for example:
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) |