margherita pizza
margherita pizza

Reputation: 7145

Sequlize js how to do date comparison based on CURRENT_DATE

excuting this on the phpMyAdmin gives me a one record.

SELECT * FROM `banners` WHERE region_id = 1 AND status= 'approved' and approved_date = CURRENT_DATE;

But I try to achive same thing using sequlize like this

const banners = await db.banners.findAll({
      where: {
        region_id: id,
        status: "approved",
        approved_date: new Date()
      }
    });

When I trace the query

SELECT id, path, expire_date, status, fee, notes, approved_date, region_id, restaurant_id, is_paid, createdAt, updatedAt FROM banners AS banners WHERE banners.region_id = 1 AND banners.status = 'approved' AND banners.approved_date = '2018-10-11 17:29:31';

The problem I see is approved_date column data type is date and the comparison new Date() both the date and the time. What is the similar key word to CURRENT_DATE in sequlize

Upvotes: 0

Views: 620

Answers (2)

margherita pizza
margherita pizza

Reputation: 7145

This answer also works!

const banners = await db.banners.findAll({
      where: {
        region_id: id,
        status: "approved",
        approved_date: db.Sequelize.fn('CURRENT_DATE')

      }

    });

Upvotes: 0

mcranston18
mcranston18

Reputation: 4790

If you want to pass a string directly to the WHERE condition, you can use sequelize.literal:

const banners = await db.banners.findAll({
  where: {
    $and: [
      {
        region_id: id,
        status: "approved"
      }
    ],
    sequelize.where(
      sequelize.fn('DATE', sequelize.col('approved_date')),
      sequelize.literal('CURRENT_DATE')
    )
  }
});

Upvotes: 2

Related Questions