在查询中分离位置

huangapple go评论104阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年3月24日 05:08:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/36188706.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定