I am exploring the capabilities of AdonisJs query builder by referring to their documentation at
Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section:
const query = Database.table('users')
if (username) {
query.where('username', username)
}
Unfortunately, when implementing this in my backend code, it results in an error.
My objective is to execute conditional where queries. There are situations where I require the where clause, while in other cases, all data needs to be retrieved based on a boolean value without applying any where conditions.
I have observed that the 'query' variable (in the example above) can only be chained effectively when connected to the Database class directly. Attempting to save it as a standalone variable leads to errors, such as query.where(...)
.
At present, my workaround involves creating separate queries using the Database class for all possible combinations of 3 boolean conditions, resulting in 9 different queries. However, as I anticipate more conditions in the future, this approach may become impractical.
Is there a more efficient way to handle conditional where queries in AdonisJs?
P.S: While I am aware that multiple fields can be included in a single where clause like
.where({ field1: true, field2: false})
, this is not directly related to my current issue.