在Sequelize js的范围内同时使用“AND”和“OR”

时间:2018-02-11 21:21:42

标签: javascript express orm sequelize.js

使用可爱的Sequelize JS遇到更多麻烦。

我正在尝试将以下查询放入Sequelize范围。

SELECT *
FROM Projects
WHERE isDeleted IS NOT true
AND ( 
    ( importSource IS NOT null ) AND ( createdAt BETWEEN '2018-01-19' AND '2018-01-29') 
    OR 
    ( importSource IS null ) AND ( createdAt > '2018-01-19' )
)

此刻尝试这一点在我的模型中无济于事。

scopes: {
  active: {
    where: {
      isDeleted: {
        [Op.not]: true
      },
      [Op.or]: [
        {
          importSource: { [Op.ne]: null },
          createdAt: {
            [Op.between]: [
              new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
              new Date(new Date() - 4 * (24 * 60 * 60 * 1000))
            ],
          }
        },
        {
          importSource: { [Op.eq]: null },
          createdAt: {
            [Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
          }
        }
      ]
    }
  }
}

没有错误。就是这个正在运行的MySQL。

Executing (default): SELECT `id`, `url`, `title`, `company`, `importSource`, `importSourceId`, `publishedAt`, `createdAt`, `updatedAt` FROM `Projects` AS `Project` WHERE `Project`.`isDeleted` IS NOT true ORDER BY `Project`.`id` DESC LIMIT 5;

这是调用模型和范围的控制器方法。

exports.index = (req, res) => {
  const MAX = 50;
  var numberProjects = ((req.query.number) ? req.query.number : MAX);
  numberProjects = ((numberProjects > MAX) ? MAX : numberProjects);

  Project.scope('active').findAll({
    order: [
      ['id', 'DESC']
    ],
    limit: +numberProjects
  })
  .then( projects => {
    res.send( projects );
  })
};

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:2)

在问到这个问题后20分钟解决这个问题。

[Op.or]更改为$or似乎有效。

scopes: {
  active: {
    where: {
      isDeleted: { [Op.not]: true },
      $or: [
        {
          importSource: { [Op.ne]: null },
          createdAt: {
            [Op.between]: [
              new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
              new Date(new Date() - 4 * (24 * 60 * 60 * 1000))
            ],
          }
        },
        {
          importSource: { [Op.eq]: null },
          createdAt: {
            [Op.gt]: new Date(new Date() - 30 * ( 24 * 60 * 60 * 1000)),
          }
        }
      ]
    }
  }
}