Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Timestamp with date in sequelize query

I have createdAt column which stores value as "2018-11-07 15:03:16.532+00". I want to write query like select * from table_name where createdAt = input_date, where myinput_date is only date value like 2018-11-07. How do i write this query using Sequelize?

like image 609
Vijesh Avatar asked Nov 21 '18 15:11

Vijesh


2 Answers

try using the sequelize.fn() argument, for example like this, try adjusting it.

Ex:

TableName.findAll({
  where: sequelize.where(sequelize.fn('date', sequelize.col('createdAt')), '=', '2018-11-07')
})
like image 81
Sigit Avatar answered Sep 23 '22 11:09

Sigit


The accepted answer should work fine, but if we have multiple conditions in where I am using this -

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']],
        });

Generated Query:

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;
like image 30
Gvs Akhil Avatar answered Sep 21 '22 11:09

Gvs Akhil