如何在sequelize中选择一个值作为列

时间:2017-01-19 18:52:59

标签: node.js sequelize.js

如何在sequelize中执行此SELECT 'OLD' AS CUSTOM_COLUMN FROM TABLE的SQL查询?

2 个答案:

答案 0 :(得分:0)

您可以使用 sequelize.literal 来实现这一点。

const response = await YourModel.findAll({
        where: {
            ...attributes
        },
        attributes: [
            'column_name_on_model',
            [sequelize.literal("'OLD'"), 'CUSTOM_COLUMN'], //custom column name
        ],
        raw: true
    });

答案 1 :(得分:-1)

如果您为表格设置了模型,则可以在模型定义中为该列添加别名:

{
  CUSTOM_COLUMN: {
     type: Sequelize.STRING,
     field: 'OLD'
  }
}

然后将查询限制到该列:

MyModel.find all({ attributes: ['CUSTOM_COLUMN'] })

(见http://sequelize.readthedocs.io/en/v3/docs/models-definition/