从sequelize.js中的关联模型加载属性 [英] Load attributes from associated model in sequelize.js
本文介绍了从sequelize.js中的关联模型加载属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型.用户和管理员
I have two models. User and Manager
用户模型
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
}
})
最小化模型以简单地解决问题
Models are minified to simplyfy the problem
协会..
User.belongsTo(models.Manager, {
foreignKey: 'RelationshipId',
as: 'RM'
});
Manger.hasMany(model.User, {
foreignKey: 'RelationshipId',
as: "Users"
})
因此,在user.findAll()
So, on 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? 是否可以以某种方式从急切加载的模型中加载属性,而无需将它们嵌套在单独的对象下? 我希望得到的对象看起来像对象
How can I move 'ManagerName' attribute from Manager model (associated as RM) to UserObject? Is it possible to somehow load attributes from eagerly-loaded models without nesting them under a separate object? I expected the resulting Object to look Like the object
预期对象-
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
与attributes
选项一起添加即可获得所需的对象格式.
Adding raw: true
along with attributes
option worked to get the desired object format.
所以
var userObject = models.User.findAll({
raw:true,
attributes: {
include: [Sequelize.col('RM.ManagerName'), 'ManagerName']
},
include: [{
model: models.Manager,
required: false,
as: 'RM',
attributes: []
}]
});
这篇关于从sequelize.js中的关联模型加载属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文