Centell
Centell

Reputation: 409

Sequelize function on where

I using sequelize 5.21.2 on Node 12.

I want to get like this:

SELECT `id`
FROM `order`
WHERE (substr(`order`.`code`,1,8) >= '20200101'
AND substr(`order`.`code`,1,8) <= '20201230')

So I wrote it like this:

return Model.order.findAll({
  attributes: [
    'id',
  ],
  where: {
    [sequelize.fn('substr', Model.sequelize.col('code'), 1, 8)]: {
      [Op.gte]: params.start_date,
      [Op.lte]: params.end_date,
    },
  },
});

But It returns:

SELECT `order`.`id`
FROM `order`
WHERE (`order`.`[object Object]` >= '20200101'
AND `order`.`[object Object]` <= '20201230')

I tried

[sequelize.literal('STR_TO_DATE(substr(code,1,8),\'%Y %m %d\')'), 'order_date']
[sequelize.literal('STR_TO_DATE(substr(code,1,8),\'%Y %m %d\')')]
[sequelize.fn('substr', Model.sequelize.col('code'), 1, 8)]

but they work fine when I SELECT, but not WHERE.

How do I get the results I want? I couldn't find any relevant information in the official manual.. (https://sequelize.org/v5/manual/querying.html#where)

Upvotes: 4

Views: 2192

Answers (1)

doublesharp
doublesharp

Reputation: 27599

Use sequelize.where and Op.and to generate the select statement using a function and not a column. See this page in the Sequelize documentation - Advanced queries with functions (not just columns)

const { sequelize, order } = Model;
return order.findAll({
  attributes: [
    'id',
  ],
  where: {
    [Op.and]: [
      sequelize.where(sequelize.fn('substr', sequelize.col('code'), 1, 8), {
        [Op.gte]: params.start_date,
      }),
      sequelize.where(sequelize.fn('substr', sequelize.col('code'), 1, 8), {
        [Op.lte]: params.end_date,
      }),
    ],
  },
});

Upvotes: 7

Related Questions