You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 13:02:07