I need to separate where
to validates values with conditional, Example
email := "[email protected]"
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 '%[email protected]%'
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 '%[email protected]%' and users.name LIKE '%jhon%'
Thanks!
I believe this should work:
chain := db.Where("users.name like ?", "%"+jhon+"%")
email := "[email protected]"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With