简体   繁体   中英

How to select case query in sequelize?

I have a sql query:

SELECT field1, field2,
  CASE
    WHEN field1=1 THEN 'a'
    ELSE 'b'
  END 
  AS field3
FROM test

and I want to implement it with sequelizejs ,

const params = {
  attributes: //DO SELECT CASE,
};

yield Model.findAll(params);

Can anyone help me? Thank you.

For the people that are still looking for this answer

Model.findAll({
  attributes: [[models.sequelize.literal('CASE WHEN "field1" = true THEN 55 ELSE 23 END'), 'field3']]
}

or

Model.findAll({
  attributes: { include: [[models.sequelize.literal('CASE WHEN "field1" = true THEN 55 ELSE 23 END'), 'field3']]}
}

So in my example when field1 is true it will return 55 else 23. This will generate a query like

SELECT CASE WHEN "field1" THEN 55 ELSE 23 END AS "field3" FROM "models"

For more information you can look in the documentation http://docs.sequelizejs.com/en/latest/docs/querying/#attributes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM