如何使用Sequelize查询tstzrange?

时间:2019-06-27 10:00:18

标签: node.js postgresql sequelize.js

我有一个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错误。如何正确格式化查询以获得所需的内容?

1 个答案:

答案 0 :(得分:0)

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

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