如何在sequelize中选择案例查询?

时间:2016-11-07 10:04:00

标签: javascript sql node.js postgresql sequelize.js

我有一个SQL查询:

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

我希望用sequelizejs

来实现它
const params = {
  attributes: //DO SELECT CASE,
};

yield Model.findAll(params);

任何人都可以帮助我吗?谢谢。

1 个答案:

答案 0 :(得分:8)

对于仍在寻找此答案的人

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

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

因此,在我的示例中,当field1为true时,它将返回55 else 23.这将生成类似

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

有关详细信息,请查看文档 http://docs.sequelizejs.com/en/latest/docs/querying/#attributes