Can I conditionally add a where() clause to my knex query?

后端 未结 4 982
你的背包
你的背包 2020-12-08 02:32

I want to add a where() clause in my query, but conditionally. Specifically, I want it added only if a sepecific querystring parameter is passe

相关标签:
4条回答
  • 2020-12-08 02:46

    You can do it by checking if your query string is present and running a different query.

    router.get('/questions', function(req, res) {
      if (req.query.yourQueryString) {
        // Run your more specific select
      } else {
        knex('questions').select('question', 'correct', 'incorrect').limit(50).where(
            'somecolumn', req.query.param) // <-- only if param exists
          .then(function(results) {
            res.send(results);
          });
      }
    }
    });

    0 讨论(0)
  • 2020-12-08 02:49

    Yes. Use modify.

    As applied to your example:

    router.get('/questions', function (req, res) {
        knex('questions')
            .select('question', 'correct', 'incorrect')
            .limit(50)
            .modify(function(queryBuilder) {
                if (req.query.param) {
                    queryBuilder.where('somecolumn', req.query.param);
                }
            })   
            .then(function (results) {
                res.send(results);
            });
    });
    
    0 讨论(0)
  • 2020-12-08 02:50

    You can actually use query builder inside .where() like so:

    .where((qb) => {condition == true ? do something if true : do something if false })
    

    IMO @ItaiNoam answer should be correct with .modify()

    0 讨论(0)
  • 2020-12-08 02:57

    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);
      });
    });
    
    0 讨论(0)
提交回复
热议问题