在sequelize.js中加载关联模型的属性

时间:2018-04-24 07:22:30

标签: sql node.js orm sequelize.js

我有两个型号。用户和经理

用户模型

 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的属性? 是否有可能以某种方式加载来自热切负载模型的属性而不将它们嵌套在单独的对象下? 我希望生成的Object看起来像对象

预期对象 -

userObject = [{
        UserId: 1,
        RelationshipId: 4545,
        UserName: 'Jon',
        ManagerName: 'Sam' // <-- from Manager model
    },
    {
        UserId: 2,
        RelationshipId: 432,
        UserName: 'Jack',
        ManagerName: 'Phil' // <-- from Manager model
    },
    ...
]

谢谢。

1 个答案:

答案 0 :(得分:0)

添加raw: trueattributes选项可以获得所需的对象格式。

所以,

var userObject = models.User.findAll({
raw:true,
attributes: {
include: [Sequelize.col('RM.ManagerName'), 'ManagerName']
},
    include: [{
        model: models.Manager,
        required: false,
        as: 'RM',
        attributes: []
    }]
});