【问题标题】:Sequelize include return data formatSequelize 包含返回数据格式
【发布时间】:2020-10-27 07:46:10
【问题描述】:

我有一个模型User 和表userRole 作为模型UserRole 有一个来自User 表的外键userId

我已使用此查询来获取一个用户的 userRole 详细信息:

const userFound = await User.findAll({
        where: { userId },
        attributes: { exclude: ["password"] },
        include: {
            model: UserRole,
            as: "userRole",
            require: true,
        },
    })

返回值为:

[
    {
        "userId": 36,
        "firstName": "a",
        "lastName": "b",
        "userRole": {
            "userId": 36,
            "userRoleId": 3
        }
    },
    {
        "userId": 36,
        "firstName": "a",
        "lastName": "b",
        "userRole": {
            "userId": 36,
            "userRoleId": 5
        }
    }
]

如何使 userRole 返回为一个嵌套数组,例如:

[
    {
        "userId": 36,
        "firstName": "a",
        "lastName": "b",
        "userRole": [
            {
                "userId": 36,
                "userRoleId": 3
            },
            {
                "userId": 36,
                "userRoleId": 5
            },
        ]
    }
]

更新: 我设置的关系是:

User.belongsTo(UserRole, { targetKey: "userId", foreignKey: "userId", as: "userRoles" })
UserRole.hasMany(User, { sourceKey: "userId", foreignKey: "userId", as: "users" })

【问题讨论】:

    标签: node.js express sequelize.js


    【解决方案1】:

    我想你有这样的关联:

    User.hasOne(UserRole, { foreignKey: 'userId', as: 'userRole' }); 
    

    您应该将其替换为(因为一个用户有多个角色):

    User.hasMany(UserRole, { foreignKey: 'userId', as: 'userRole' });
    

    【讨论】:

      【解决方案2】:

      您需要在查询前添加User和UserRole之间的关联。

      UserRole.belongsTo(User, { as: 'user', foreignKey: 'userId', targetKey: 'userId' }); User.hasMany(UserRole, { as: 'userRole', foreignKey: 'userId', sourceKey: 'userId' });

      https://sequelize.org/master/manual/assocs.html#one-to-many-relationships

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-04
        • 2019-07-30
        • 1970-01-01
        • 2020-06-17
        • 2018-09-25
        • 1970-01-01
        • 1970-01-01
        • 2018-10-05
        相关资源
        最近更新 更多