Sequelize 带有日期的 Where 语句

2022-01-19 00:00:00 node.js javascript sequelize.js

我使用 Sequelize 作为我的后端 ORM.现在我想在日期上做一些 WHERE 操作.

I am using Sequelize as my backend ORM. Now I wish to do some WHERE operations on a Date.

更具体地说,我想获取日期介于现在和 7 天前之间的所有数据.

More specifically, I want to get all data where a date is between now and 7 days ago.

问题是文档没有指定可以对 Datatypes.DATE

The problem is that the documentation does not specify which operations you can do on Datatypes.DATE

谁能指出我正确的方向?

Can anyone point me in the right direction?

推荐答案

就像 Molda 说的,你可以使用 $gt, $lt, $gte$lte 带日期:

Just like Molda says, you can use $gt, $lt, $gte or $lte with a date:

model.findAll({
  where: {
    start_datetime: {
      $gte: moment().subtract(7, 'days').toDate()
    }
  }
})

如果您使用的是 Sequelize v5,则必须包含 Op 因为密钥已移至 Symbol

If you're using v5 of Sequelize, you've to include Op because the key was moved into Symbol

const { Op } = require('sequelize')

model.findAll({
  where: {
    start_datetime: {
      [Op.gte]: moment().subtract(7, 'days').toDate()
    }
  }
})

在此处查看更多续集文档

相关文章