【问题标题】:How do I query a tstzrange with Sequelize?如何使用 Sequelize 查询 tstzrange?
【发布时间】:2019-11-09 07:58:34
【问题描述】:

我有一个range of timestamp with timezone 存储在我的 PostgreSQL 数据库的一列中,例如:

timeRange (tstzrange)
["2019-02-10 23:00:00+00","2019-03-09 23:00:00+00")

我想根据该列查询我的数据库,测试给定的日期范围是否包含在我的列中的范围内。


根据PostgreSQL docs,我可以用<@操作符查询另一个范围包含的范围:

 Operator | Description           | Example                          | Result
 <@       | range is contained by | int4range(2,4) <@ int4range(1,7) | t

根据Sequelize docs,这可以使用运算符$contained来完成:

$contained: [1, 2]     // <@ [1, 2) (PG range is contained by operator)

我曾尝试使用此运算符进行查询:

const start = '2019-02-11T00:30:00.000Z';
const end = '2019-02-08T02:30:00.000Z';
MyModel.findOne({
    where: {
        timeRange: {
            $contained:
                [
                    new Date(start),
                    new Date(end)
                ]
        }
    }
});

这不起作用并得到错误

error: operator does not exist: tstzrange = timestamp with time zone

查询如下所示

'SELECT * FROM "model" AS "model" WHERE  "model"."timeRange" = \'2019-06-26 22:00:00.000 +00:00\'::timestamptz;'

这可能解释了我收到 PostgreSQL 错误的原因。如何正确格式化查询以获得我想要的?

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    使用这个类似的问题,我想出了一个解决方法,但我不确定它为什么或如何工作:Query with date range using Sequelize request with Postgres in Node

    var Sequelize = require('sequelize');
    const Op = Sequelize.Op;
    const start = '2019-02-11T00:30:00.000Z';
    const end = '2019-02-08T02:30:00.000Z';
    MyModel.findOne({
        where: {
            timeRange: {
                [Op.contained]: 
                    [
                        new Date(start),
                        new Date(end)
                    ]
            }
        }
    });
    

    如果有人有解释,我很乐意听到它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      • 2019-09-05
      • 1970-01-01
      • 2014-09-10
      • 2018-03-22
      • 2017-01-19
      • 1970-01-01
      相关资源
      最近更新 更多