英文:
Separate where in query
问题
我需要将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%'
谢谢!
英文:
I need to separate where
to validates values with conditional, Example
email := "test@test.com"
if email != "" {
db.Where("users.email LIKE ?", "%"+email+"%")
}
db.Where("users.name like ?", "%"+jhon+"%").Find(&users)
That returns two queries:
1: SELECT "users".* FROM "users" WHERE users.email LIKE '%test@test.com%'
2: SELECT "users".* FROM "users" WHERE users.name LIKE '%jhon%'
but I need the result in only one query:
SELECT "users".* FROM "users" WHERE users.email LIKE '%test@test.com%' and users.name LIKE '%jhon%'
Thanks!
答案1
得分: 15
我相信这应该可以工作:
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
)都会返回一个结果,可以链式调用。这意味着你可以继续在其上调用方法,直到得到你喜欢的结果。
英文:
I believe this should work:
chain := db.Where("users.name like ?", "%"+jhon+"%")
email := "test@test.com"
if email != "" {
chain = chain.Where("users.email LIKE ?", "%"+email+"%")
}
chain.Find(&users)
All of the Gorm methods like Where
return a result, which is chainable. That means that you can continue calling methods on it until you get something that you like.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论