Sequelize查询筛选创建时间恰好满一年的Grant记录问题
问题分析
你的原查询逻辑错误,直接将created_at与时间间隔interval '1 year'比较,这不符合“恰好满一年”的需求——数据库无法将日期和纯时间间隔做有效对比,导致查询结果不符合预期。
正确查询写法
根据“恰好满一年”的两种常见需求,提供对应的Sequelize实现:
1. 匹配日期部分(忽略时分秒)
获取created_at的日期恰好是一年前今天的所有记录(例如今天是2025-10-08,匹配所有2024-10-08创建的记录):
方式一:使用Sequelize内置函数(推荐,避免硬编码表名)
const { Op, fn, col } = require('sequelize'); const newGrants = await this.Application.findAll({ where: { applied_by: userIds, }, include: { model: this.Grant, where: { [Op.eq]: [ fn('DATE', col('Grant.created_at')), fn('DATE', fn('NOW', '- INTERVAL 1 YEAR')) ] } } });
方式二:使用原生SQL字面量
const { literal } = require('sequelize'); const newGrants = await this.Application.findAll({ where: { applied_by: userIds, }, include: { model: this.Grant, where: literal(`DATE("Grant"."created_at") = DATE(NOW() - INTERVAL '1 year')`) } });
2. 精确匹配时间(包含时分秒)
获取created_at加上一年后恰好等于当前时间的记录(精确到秒级):
PostgreSQL版本
const { literal } = require('sequelize'); const newGrants = await this.Application.findAll({ where: { applied_by: userIds, }, include: { model: this.Grant, where: literal(`"Grant"."created_at" + INTERVAL '1 year' = NOW()`) } });
MySQL版本
const { literal } = require('sequelize'); const newGrants = await this.Application.findAll({ where: { applied_by: userIds, }, include: { model: this.Grant, where: literal(`DATE_ADD("Grant"."created_at", INTERVAL 1 YEAR) = NOW()`) } });
注意事项
- 确保
this.Grant与this.Application的关联配置正确 - 若直接写表名字段,需与数据库中实际表名/字段名大小写匹配,推荐用
col('Grant.created_at')动态引用字段避免出错 - 不同数据库的日期函数语法有差异,需根据你使用的数据库调整对应写法
内容的提问来源于stack exchange,提问作者Numaira Nawaz
相关产品推荐
相关产品推荐

