[英]How do I select a column using an alias
如何执行这样的 sql 查询?
SELECT column_name AS alias_name FROM table_name;
示例:我希望将“first”列选为“firstname”
Table.findAll({
attributes: [id,"first"]
})
.then(function(posts) {
res.json(posts);
})
Table.findAll({
attributes: ['id', ['first', 'firstName']] //id, first AS firstName
})
.then(function(posts) {
res.json(posts);
});
Sequelize 也支持直接在模型定义上定义列名。
Sequelize Docs他们提到关于列定义的field
属性。
例如:(取自 Docs 本身)
const { Model, DataTypes, Deferrable } = require("sequelize");
class Foo extends Model { }
Foo.init({
// You can specify a custom column name via the 'field' attribute:
fieldWithUnderscores: {
type: DataTypes.STRING,
field: 'field_with_underscores'
},
}, {
sequelize,
modelName: 'foo'
});
感谢这个答案
您需要使用row.get('newname')
访问由attributes
别名的列
由于某种原因,只执行row.newname
或row.oldname
将无法像处理非别名名称那样工作:
https://sequelize.org/v5/manual/models-usage.html记录它:
Project.findOne({ where: {title: 'aProject'}, attributes: ['id', ['name', 'title']] }).then(project => { // project will be the first entry of the Projects table with the title // 'aProject' || null // project.get('title') will contain the name of the project })
但是https://sequelize.org/v5/manual/models-usage.html没有提到它,这令人困惑:
instance.field // is the same as instance.get('field')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.