【发布时间】:2018-10-04 08:36:07
【问题描述】:
我有两个模型。用户和管理员
用户模型
const UserMaster = sequelize.define('User', {
UserId: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
RelationshipId: {
type: DataTypes.STRING,
allowNull: true,
foreignKey: true
},
UserName: {
type: DataTypes.STRING,
allowNull: true
}
})
经理模型
const Manager = sequelize.define('Manager', {
ManagerId: {
type: DataTypes.BIGINT,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
RelationshipId: {
type: DataTypes.STRING,
allowNull: true,
foreignKey: true
},
MangerName: {
type: DataTypes.STRING,
allowNull: true
}
})
模型被缩小以简化问题
协会..
User.belongsTo(models.Manager, {
foreignKey: 'RelationshipId',
as: 'RM'
});
Manger.hasMany(model.User, {
foreignKey: 'RelationshipId',
as: "Users"
})
所以,在 user.findAll() 上
var userObject = models.User.findAll({
include: [{
model: models.Manager,
required: false,
as: 'RM',
attributes: ['ManagerName']
}]
});
我得到以下信息。
userObject = [{
UserId: 1,
RelationshipId: 4545,
UserName: 'Jon',
RM: {
ManagerName: 'Sam'
}
},
{
UserId: 2,
RelationshipId: 432,
UserName: 'Jack',
RM: {
ManagerName: 'Phil'
}
},
...
]
如何将“ManagerName”属性从 Manager 模型(关联为 RM)移动到 UserObject? 是否可以以某种方式从急切加载的模型中加载属性而不将它们嵌套在单独的对象下? 我希望生成的对象看起来像对象
预期对象--
userObject = [{
UserId: 1,
RelationshipId: 4545,
UserName: 'Jon',
ManagerName: 'Sam' // <-- from Manager model
},
{
UserId: 2,
RelationshipId: 432,
UserName: 'Jack',
ManagerName: 'Phil' // <-- from Manager model
},
...
]
谢谢。
【问题讨论】:
-
使用
raw = true否则sequelize 总是会这样做 -
但这会返回给我 RM.ManagerName。如何将其重命名(或操纵)为仅 ManagerName ?
-
进一步添加 ` 属性:{ 包括:[Sequelize.col('RM.ManagerName'), 'ManagerName'] }` 工作。谢谢@Elebkey
标签: sql node.js orm sequelize.js