将时间戳记与序列查询中的日期进行比较

时间:2018-11-21 15:44:36

标签: javascript node.js postgresql sequelize.js timestamp-with-timezone

我有createdAt列,其值存储为"2018-11-07 15:03:16.532+00"。 我想编写类似select * from table_name where createdAt = input_date的查询,其中我的input_date仅是日期值,例如2018-11-07。 如何使用 Sequelize 编写此查询?

2 个答案:

答案 0 :(得分:0)

尝试使用sequelize.fn()参数,例如,像这样,尝试调整它。

例如:

TableName.findAll({
  where: sequelize.where(sequelize.fn('date', sequelize.col('createdAt')), '=', '2018-11-07')
})

答案 1 :(得分:0)

可接受的答案应该可以正常工作,但是如果我们在使用该条件的多个条件下-

const cashRegisterData = await cashRegisterMain.findAll({
            attributes: ['crmid', 'dateCreated', 'startDate', 'endDate', 'startAmount', 'finalAmount', 'status'],
            where: {
                createdBy: userId,
                [Op.and]: [
                    sequelize.where(sequelize.fn('date', sequelize.col('dateCreated')), '>=', fromDate),
                    sequelize.where(sequelize.fn('date', sequelize.col('dateCreated')), '<=', toDate),
                ]
            },
            order: [['dateCreated', 'DESC']],
        });

生成的查询:

SELECT `crmid`, `dateCreated`, `startDate`, `endDate`, `startAmount`, `finalAmount`, `status` FROM `cashRegisterMain` AS `cashRegisterMain` WHERE (date(`dateCreated`) >= '2020-11-20' AND date(`dateCreated`) <= '2020-11-20') AND `cashRegisterMain`.`createdBy` = 1 ORDER BY `cashRegisterMain`.`dateCreated` DESC;