我需要单独的where
来验证带有条件的值,示例
email := "test@test.com"
if email != "" {
db.Where("users.email LIKE ?", "%"+email+"%")
}
db.Where("users.name like ?", "%"+jhon+"%").Find(&users)
返回两个查询:
1:SELECT "users".* FROM "users" WHERE users.email LIKE '%test@test.com%'
2:SELECT "users".* FROM "users" WHERE users.name LIKE '%jhon%'
但我只需要一个查询中的结果:
SELECT "users".* FROM "users" WHERE users.email LIKE '%test@test.com%' and users.name LIKE '%jhon%'
谢谢!
答案 0 :(得分:4)
我相信这应该有效:
chain := db.Where("users.name like ?", "%"+jhon+"%")
email := "test@test.com"
if email != "" {
chain = chain.Where("users.email LIKE ?", "%"+email+"%")
}
chain.Find(&users)
所有Gorm方法(如Where
)都会返回一个可链接的结果。这意味着你可以继续调用它上面的方法,直到得到你喜欢的东西。