最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

使用带有Postgres的Sequelize请求在节点中查询日期范围

运维笔记admin14浏览0评论

使用带有Postgres的Sequelize请求在节点中查询日期范围

使用带有Postgres的Sequelize请求在节点中查询日期范围

我正在尝试通过在Node.js中使用Sequelize ORM在两个日期之间获取行。我正在使用PostgreSQL。问题是Sequelize错误地解释了我正在发出的请求。

这是我用来发出请求的代码

const dbresp = await Table.findAll({
  attributes: [...],
  where: {
    ...
    createdAt: {
       $between: [new Date(Date(startDate)), new Date(Date(endDate))],
       // same effect
       // $lte: new Date(startDate),
       // $gte: new Date(endDate),
    },
  },
  logging: console.log,
  raw: true,
  order: [['createdAt', 'ASC']],
  // limit: count,
});

通过记录原始SQL请求,很明显该请求不正确

SELECT ...
FROM "table" AS "table"
WHERE "table"."createdAt" = '2019-02-05 21:00:00.000 +00:00'
      "table"."createdAt" = '2019-02-05 21:00:00.000 +00:00'
ORDER BY "table"."createdAt" ASC;

提出此类请求的正确方法是什么?我应该使用原始查询吗?

我已经用谷歌搜索了这个问题,但是没有StackOverflow等GitHub帮助了。

回答如下:

确定,IDK会导致此问题,但我通过使用Sequelize的Op对象来解决此问题。

const Op = require('./models').Sequelize.Op;
const dbresp = await Table.findAll({
  attributes: [...],
  where: {
    ...
    createdAt: {
       [Op.between]: [startDate, endDate],
    },
  },
  logging: console.log,
  raw: true,
  order: [['createdAt', 'ASC']],
  // limit: count,
});

似乎$ between运算符不起作用

发布评论

评论列表(0)

  1. 暂无评论