2014-12-01 26 views
11

Sorguma where() yan tümcesi eklemek istiyorum, ancak koşullu olarak. Özellikle, URL'ye yalnızca sepecific querystring parametresi iletildiğinde eklenmesini istiyorum. Bu mümkün mü ve eğer öyleyse, bunu yapmayı nasıl yaparım?Knex sorgum için koşullu olarak bir where() cümlesi ekleyebilir miyim?

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); 
     }); 
}); 

cevap

5

Bunu, onu çalıştırmak sonra koşullu uygulamak nerede fıkra ve bir değişkende Sorgunuzla saklayabilirsiniz:

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); 
    }); 
}); 
-4

Sorgu dizginizin var olup olmadığını ve farklı bir sorgu çalıştırıp çalıştırmadığını kontrol ederek yapabilirsiniz.

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); 
 
     }); 
 
    } 
 
} 
 
});

19

Evet. modify'u kullanın.

olarak sizin örneğe uygulanan:

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

Teşekkür! Bence şöyle olmalı: if (req.query.param) { queryBuilder.where ('somecolumn', req.query.param); } –

+0

Bu, benim için çalıştı. Çok teşekkür ederim! –

+0

Bu kodda küçük hata var. Bu '' 'yerine' queryBuilder.where 'olmalıdır –

İlgili konular