Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate where in query

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!

like image 566
kalelc Avatar asked Mar 23 '16 21:03

kalelc


1 Answers

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.

like image 168
robbrit Avatar answered Oct 06 '22 05:10

robbrit