我有一个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);
任何人都可以帮助我吗?谢谢。
答案 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