序列化查询以根据created_at日期过滤一年前创建的记录

问题描述 投票:0回答:1

我正在 Node.js 应用程序中使用 Sequelize,需要编写一个查询来检索

created_at
日期恰好是一年前的数据。

这是我当前使用的查询:

             const newGrants = await this.Application.findAll({
                where: {
                    applied_by: userIds,
                },
                include: {
                    model: this.Grant,
                    where: {
                        // Using a raw SQL literal to add one year to the `created_at` date
                        [Op.and]: literal(`"grant"."created_at" <=  interval '1 year'`)
                    }
                }
            });

但是,这个查询似乎没有按预期工作。我不确定如何正确设置条件格式以过滤一岁之间的created_at日期。如何调整查询以正确过滤创建时间在一年之间的记录?

我尝试过使用原始 SQL 文字,但它似乎无法正常工作。任何关于如何在 Sequelize 中实现这一目标的指导将不胜感激。

我想从

Grant
模型中检索记录,其中
created_at
日期正好是拨款创建日期后一年。

javascript mysql node.js sequelize.js
1个回答
0
投票

const { Op } = require('sequelize');

// Assuming your model is named 'YourModel'
const YourModel = require('./path/to/your/model');

// Get the current date
const currentDate = new Date();

// Calculate the date exactly one year ago from the current date
const oneYearAgo = new Date(currentDate.getFullYear() - 1, currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds());

// Perform the query
return YourModel.findAll({
  where: {
    createdDate: {
      [Op.gte]: oneYearAgo,
      [Op.lt]: currentDate,
    },
  },
});

您可以通过从当前日期的年份减去一年并保留相同的月、日、小时、分钟和秒来计算 oneYearAgo 日期。然后,我们使用 Op.gte 运算符查找大于或等于 oneYearAgo 的记录,并使用 Op.lt 运算符查找小于 currentDate 的记录。这样,我们就可以检索创建日期在过去一年内的记录。

© www.soinside.com 2019 - 2024. All rights reserved.