Your Question
//这是官网对分组查询的描述 https://gorm.io/docs/advanced_query.html#Group-Conditions
db.Where( db.Where("pizza = ?", "pepperoni").Where(db.Where("size = ?", "small").Or("size = ?", "medium")),).Or( db.Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"),).Find(&Pizza{}).Statement
// SELECT * FROM `pizzas` WHERE (pizza = "pepperoni" AND (size = "small" OR size = "medium")) OR (pizza = "hawaiian" AND size = "xlarge")
但实际上不是这样的 我测试后的结果是
//实际结果
SELECT
*
FROM
`test_models`
WHERE
pizza = 'pepperoni'
AND size = 'small'
OR size = 'medium'
AND ( pizza = 'pepperoni' AND size = 'small' OR size = 'medium' )
AND (
pizza = 'pepperoni'
AND size = 'small'
OR size = 'medium'
AND ( pizza = 'pepperoni' AND size = 'small' OR size = 'medium' ))
AND pizza = 'hawaiian'
AND size = 'xlarge'
OR (
pizza = 'pepperoni'
AND size = 'small'
OR size = 'medium'
AND ( pizza = 'pepperoni' AND size = 'small' OR size = 'medium' )
AND (
pizza = 'pepperoni'
AND size = 'small'
OR size = 'medium'
AND ( pizza = 'pepperoni' AND size = 'small' OR size = 'medium' ))
AND pizza = 'hawaiian'
AND size = 'xlarge')
//正确的写法
db.Where(
db.Session(&gorm.Session{NewDB: true}).Unscoped().Where("pizza = ?", "pepperoni").Where(db.Where("size = ?", "small").Or("size = ?", "medium")),
).Or(
db.Session(&gorm.Session{NewDB: true}).Unscoped().Where("pizza = ?", "hawaiian").Where("size = ?", "xlarge"),
).Find(&pizza)
The document you expected this should be explained
Expected answer
Comment From: a631807682
Most of the documents do not describe what db is, but the default db refers to a shareable db instance, which can be created through gorm.Open or created through .Session
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:
https://gorm.io/docs/method_chaining.html#content-inner