Your Question
I'm using gorm 1.19.6. How to use group condition in gorm? My code: db.Where("a").Where("b").Or("c") Expect: select * from "table_name" where a and (b or c) Actual: select * from "table_name" where (a and b or c) Following document: https://gorm.io/docs/advanced_query.html#Group-Conditions I have 2 ways to build query which I want: 1/ db.Where("a").Where("b or c") // I think this is not good way. 2/ db.Where(a).Where("(b").Or("c)") // same as above What is right way to expose query like: select * from "table_name" where a and (b or c) by gorm. (not use raw query)?
The document you expected this should be explained
Expected answer
Comment From: lintaba
Same/similar issue.
ors := db
for i := 0; i < len(fields); i++ {
ors = ors.Or(fields[i]+"=x")
}
db.Where(ors)
--- expected:
SELECT * from t WHERE (A=x OR B=x) AND "deleted_at" IS NULL
--- actual:
SELECT * FROM t WHERE (A=x OR B=x AND (A=x OR B=x)) AND "deleted_at" IS NULL
db.Where("true")
for i := 0; i < len(fields); i++ {
if i==0 : { db.Where(fields[i]+"=x") }
if i>0 : { db.Or(fields[i]+"=x") }
}
db.Where("true")
--- expected:
SELECT * from t WHERE true AND (A=x OR B=x) AND true AND "deleted_at" IS NULL
--- actual:
SELECT * FROM t WHERE (true AND A=x OR B=x AND true) AND "deleted_at" IS NULL
--- (which is equivalent with):
SELECT * FROM t WHERE ( ( true AND A=x ) OR ( B=x AND true ) ) AND "deleted_at" IS NULL
Comment From: a631807682
var result User
DB.Where("name = ?", "jinzhu").Where(DB.Where("name = ?", "jin").Or("name = ?", "zhu")).Find(&result)
SELECT * FROM "users" WHERE name = 'jinzhu' AND (name = 'jin' OR name = 'zhu') AND "users"."deleted_at" IS NULL