如何使用$ or和$ and在续集查询中创建动态where子句

时间:2019-05-16 13:02:35

标签: sql node.js sequelize.js

我正在尝试创建动态where子句以使用续集过滤数据。但是我被困在where子句中使用“ OR”。

我尝试通过以下方式创建动态where子句

let where = {};
if(obj.NoteCat)
   where.NoteCat = obj.NoteCat;
if(obj.NoteSubCat)
   where.NoteSubCat = obj.NoteSubCat;
where.NoteEntryDate = {
        [Op.and]: {
            [Op.gte]: obj.FromDate,
            [Op.lte]: obj.ToDate,
        }
};
where.NoteWeekEndingDate = {
        [Op.and]: {
            [Op.gte]: obj.FromDate,
            [Op.lte]: obj.ToDate,
        }
}; 
await table.findAll({
    where: where,
}

我希望在下面的查询中给出

SELECT *
FROM   table     
WHERE  NoteCat = ''
AND    NoteSubCat  = ''
OR     (NoteEntryDate      >= '2019-05-16 12:52:50.931' AND NoteEntryDate      <= '2019-05-16 12:52:50.931') 
OR     (NoteWeekEndingDate >= '2019-05-16 12:52:50.931' AND NoteWeekEndingDate <= '2019-05-16 12:52:50.931')

但是实际输出是

SELECT *
FROM   table     
WHERE  NoteCat = ''
AND    NoteSubCat  = ''
AND    (NoteEntryDate      >= '2019-05-16 12:52:50.931' AND NoteEntryDate      <= '2019-05-16 12:52:50.931') 
AND    (NoteWeekEndingDate >= '2019-05-16 12:52:50.931' AND NoteWeekEndingDate <= '2019-05-16 12:52:50.931')

我如何获得预期的结果。我已经浪费了一整天了。在这方面的任何帮助都将受到高度赞赏。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以按相反的顺序创建它,如下所示:

let where = {
  [Op.or]: {
    NoteEntryDate: {
      [Op.and]: {
        [Op.gte]: obj.FromDate,
        [Op.lte]: obj.ToDate,
      }
    },
    NoteWeekEndingDate: {
      [Op.and]: {
        [Op.gte]: obj.FromDate,
        [Op.lte]: obj.ToDate,
      }
    }
  }
};
if(obj.NoteCat)
  where.NoteCat = obj.NoteCat;
if(obj.NoteSubCat)
  where.NoteSubCat = obj.NoteSubCat;
await table.findAll({
  where: where,
}