Node.js Sequelize: множественное условие для 'где' - PullRequest
0 голосов
/ 13 июля 2020

Как мне запросить таблицу с несколькими условиями? Это не дало мне ошибки, но выполнялось только первое условие!

exports.findAllLimit = (req, res) => {

 const titulo  = req.query.titulo ;
 var condition = titulo ? { titulo : { [Op.iLike]: `%${titulo }%` } } : null;
 var condition2 = {stock: {  [Op.ne]: 0}};

 Produtos.findAll({ 
 where:  condition , condition2,
 include: [Categorias], 
  order: [ 
   ['id', 'ASC']
         ],
  limit: 9
  })
.then(data => {
  res.send(data);
})
.catch(err => {
  res.status(500).send({
    message:
        err.message || "Ocorreu um erro a retirar os dados do backend!."
  });
   });
 };

Ответы [ 2 ]

3 голосов
/ 14 июля 2020

Вы создаете здесь объект со свойством condition2 и его значением. Вам нужно объединить эти 2 условия и назначить их где. поэтому вы можете использовать:

where: Object.assign({}, condition , condition2),

OR:

where: {...condition, ...condition2}
0 голосов
/ 14 июля 2020

вы можете сделать это для нескольких условий.

const titulo  = req.query.titulo ;
var condition = titulo
  ? {
      titulo: {
        [Op.iLike]: `%${titulo}%`,
      },
    }
  : null;
var condition2 = {
  stock: {
    [Op.ne]: 0,
  },
};

let where = [];
where.push(condition);
where.push(condition2);

Produtos.findAll({
  where,
});
...