【问题标题】:Load attributes from associated model in sequelize.js从 sequelize.js 中的关联模型加载属性
【发布时间】: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


【解决方案1】:

添加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: []
    }]
});

【讨论】:

  • 感谢这为我节省了很多时间。关键解决方案是使用“Sequelize.col”替换关联模型的属性名称。
  • 使用 TS 得到错误:类型 'Col' 不可分配给类型 'string |投影别名'。类型“Col”不可分配给类型“ProjectionAlias”
猜你喜欢
  • 2020-05-13
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多