Load attributes from associated model in sequelize.js

♀尐吖头ヾ 提交于 2020-05-15 17:44:54

问题


I have two models. User and Manager

User Model

 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
        }
    })

Manager model

 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

Associations..

User.belongsTo(models.Manager, {
    foreignKey: 'RelationshipId',
    as: 'RM'
});

Manger.hasMany(model.User, {
    foreignKey: 'RelationshipId',
    as: "Users"
})

So, on user.findAll()

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

I get the following.

userObject = [{
        UserId: 1,
        RelationshipId: 4545,
        UserName: 'Jon',
        RM: {
            ManagerName: 'Sam'
        }
    },
    {
        UserId: 2,
        RelationshipId: 432,
        UserName: 'Jack',
        RM: {
            ManagerName: 'Phil'
        }
    },
    ...
]

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

Expected Object --

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

Thank you.


回答1:


Adding raw: true along with attributes option worked to get the desired object format.

So,

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


来源:https://stackoverflow.com/questions/49995639/load-attributes-from-associated-model-in-sequelize-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!