node.js - 如何使用 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 错误。如何正确格式化查询以获得我想要的?
解决方案
使用这个类似的问题,我想出了一个解决方法,但我不确定它为什么或如何工作: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)
]
}
}
});
如果有人有解释,我会很高兴听到
推荐阅读
- php - CodeIgniter : 从双重关系表中查看表数据
- android - 设备重启后无法启动 Activity
- javascript - 如何在另一个创建的元素中附加元素
- r - list.files() 显示目录中除四个文件外的所有文件
- javascript - 向下移动页面的整个 html 内容?
- python - 如何用 Python 解决这个继承问题?
- android - 在领域中按日期排序
- symfony - 覆盖 Knp 菜单模板
- amazon-web-services - 旧的 AWS Lambda 层会自动删除吗?如果没有,如何删除它们?
- docker - 在 Docker compose 中将 Ceph OSD 连接到集群时出错