skip to Main Content

In MySQL, I can do:

SELECT * FROM some_table WHERE MOD(attr, 2) = 0;

it gives me all rows which attr is even.

How can I do it in Sequelize? I didn’t find in the docs.

Something like:

MyModel.findAll({
  where: {
    attr: {
        [Op.mod]: [2, 0]
    }
  }
})

2

Answers


  1. Use literal (https://sequelize.org/docs/v6/other-topics/sub-queries/) if you need full flexibility:

    MyModel.findAll({
      where: sequelize.literal('MOD(attr, 2) = 0')
    })
    

    Otherwise you can just call the desired function using fn (https://sequelize.org/docs/v6/core-concepts/model-querying-basics/#advanced-queries-with-functions-not-just-columns):

    MyModel.findAll({
      where: sequelize.where(sequelize.fn('MOD', sequelize.col('attr')), 0)
    })
    
    Login or Signup to reply.
  2. Why not sequelize.fn()? The "core concepts" docs illustrate almost exactly what you’re trying to do:

    MyModel.findAll({
      where: sequelize.where(sequelize.fn('MOD', sequelize.col('attr')), 0)
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search