首页 > 解决方案 > 如何使用 Sequelize 查询 tstzrange?

问题描述

我的 PostgreSQL 数据库的一列中存储了一系列带有时区的时间戳,例如:

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

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


根据PostgreSQL 文档,我可以使用运算符查询另一个范围包含的范围<@

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

根据Sequelize 文档,这可以使用操作符来完成$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.jspostgresqlsequelize.js

解决方案


使用这个类似的问题,我想出了一个解决方法,但我不确定它为什么或如何工作: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)
                ]
        }
    }
});

如果有人有解释,我会很高兴听到


推荐阅读