I want to add a where()
clause in my query, but conditionally. Specifically, I want it added only if a sepecific querystring parameter is passed in the URL. Is this possible, and if so, how would I go about doing it?
router.get('/questions', function (req, res) {
knex('questions')
.select('question', 'correct', 'incorrect')
.limit(50)
.where('somecolumn', req.query.param) // <-- only if param exists
.then(function (results) {
res.send(results);
});
});
You can do it by checking if your query string is present and running a different query.
You can store your query in a variable, apply your conditional where clause and then execute it, like this :
Yes. Use modify.
As applied to your example: