如何在Sequelize.js中的where子句中使用if条件

时间:2018-09-21 11:05:50

标签: postgresql sequelize.js

仅当ManufacturerId: manufacturer_id不等于null时,我才想查询manufacturer_id

我尝试了这段代码,但是它给了我语法错误:

/* Get Brands List */
router.get('/', function(req, res) {
  var archived_status = req.query["archived-status"];
  var manufacturer_id = req.params.manufacturer_id;
  models.Brand.findAll({
    where: {
        brand_archived_status: archived_status,
        if(manufacturer_id != null){
          ManufacturerId: manufacturer_id
        }
    },
    include: [{
      model: models.Job,
      required: false
    }]
  }).  
  then(function(brands) {  
      res.status(200).json(brands);  
  }, function(error) {  
      res.status(500).send(error);  
  });  
});

1 个答案:

答案 0 :(得分:2)

为什么不只在where查询之外创建整个Sequelize条件,就可以了:

let where = {
    brand_archived_status: archived_status
};
if (manufacturer_id != null) {
    where['ManufacturerId'] = manufacturer_id
}

models.Brand.findAll({
    where,
    include: [{
        model: models.Job,
        required: false
    }]
})

这看起来很简单:)