Dynamic where query

With a relational query, is there a way to change the where query based on user input? In Knex.js, we could do something like this:
knex('questions')
.select('question', 'correct', 'incorrect')
.modify(function(queryBuilder) {
if (req.query.param) {
queryBuilder.where('somecolumn', req.query.param);
}
});
knex('questions')
.select('question', 'correct', 'incorrect')
.modify(function(queryBuilder) {
if (req.query.param) {
queryBuilder.where('somecolumn', req.query.param);
}
});
3 Replies
mr_pablo
mr_pablo2y ago
Perhaps map the query params to a variable, then implement the logic, adding to the params object, then call the query with the params variable name psuedo code
const params = {...query pararms}

if (something if true) {
params.where = ...
}

db.query.findMany(params)
const params = {...query pararms}

if (something if true) {
params.where = ...
}

db.query.findMany(params)
Maston
Maston2y ago
just do something like this idk
db.query.table.findFirst({
where: (table, { eq }) => {
if (condition) {
return eq(...);
}
return eq(...);
},
});
db.query.table.findFirst({
where: (table, { eq }) => {
if (condition) {
return eq(...);
}
return eq(...);
},
});
peepoShrug
Want results from more Discord servers?
Add your server