我可以有条件地在我的knex查询中添加where()子句吗? [英] Can I conditionally add a where() clause to my knex query?
本文介绍了我可以有条件地在我的knex查询中添加where()子句吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的查询中添加 where()
子句,但有条件。具体来说,我希望只有在URL中传递了一个特定的querystring参数时才添加它。这是可能的,如果是这样,我将如何去做?
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);
});
});
推荐答案
您可以将查询存储在变量中,应用您的条件where子句然后执行它,如下所示:
You can store your query in a variable, apply your conditional where clause and then execute it, like this :
router.get('/questions', function(req, res) {
var query = knex('questions')
.select('question', 'correct', 'incorrect')
.limit(50);
if(req.query.param == some_condition)
query.where('somecolumn', req.query.param) // <-- only if param exists
else
query.where('somecolumn', req.query.param2) // <-- for instance
query.then(function(results) {
//query success
res.send(results);
})
.then(null, function(err) {
//query fail
res.status(500).send(err);
});
});
这篇关于我可以有条件地在我的knex查询中添加where()子句吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文