Reputation: 75
I'm following the query builder of AdonisJs: https://adonisjs.com/docs/4.1/query-builder#_introduction
I am trying to do something similar to the example posted under their 'Conditional Queries' subheading:
const query = Database.table('users')
if (username) {
query.where('username', username)
}
However, this sends an error on my backend.
Is there a way to do conditional where query? In some cases, I need to do have the where clause whereas in other cases based on a boolean value, I need all the data so where is not needed.
I notice that the 'query' variable (in the above example) is chainable only when it's chained to the Database class. When I save that as a variable, it throws an error (i.e. query.where(...)
throws the error).
My current solution is to have 9 possibilities for 3 boolean conditions and each of the queries will be created from Database class. I may have more than 3 conditions soon though.
Is there a way to do conditional where queries?
P.S: I do know I can have multiple fields in one where clause, although this is unrelated to my question. i.e.
.where({ field1: true, field2: false})
Upvotes: 1
Views: 1907
Reputation: 75
never mind,
const query = Database.table('users')
if (username) {
query.where('username', username)
}
works. I was using await on Database when I shouldn't have.
Upvotes: 1