用关联元数据对插入数据进行序列化

时间:2019-08-15 11:05:28

标签: node.js express sequelize.js

我的模型定义如下

User = sequelize.define('User', {....});
User.associate = models => {
    User.hasMany(models.UserPermission);
};

const Permission = sequelize.define('Permission', {...});
Permission.associate = models => {
    Permission.hasMany(models.UserPermission);
};

const UserPermission = sequelize.define('UserPermission', {...});
UserPermission.associate = models => {
    UserPermission.belongsTo(models.User);
    UserPermission.belongsTo(models.Permission);
};

enter image description here

权限是预定义的列表,并存储在“权限”表中。我想使用现有权限一次创建具有所有关联的用户。我该如何使用async和await执行此操作?

1 个答案:

答案 0 :(得分:1)

我强烈建议在您的关联上使用别名,在User上可能像这样。

User.associate = models => {
    User.hasMany(models.UserPermission, { as: 'permissions'});
};

在创建控制器上,您可以立即创建User和UserPermission,如下所示。

controller.create = async (req, res, next) => {
const user = req.body;

try {

    const userCreated = await db.User.create(user, {
        include: [{ model: db.UserPermission}]
    });

    /**
     * User object
     * user: {
     *  username: 'john',
     *  email: john@smith.com
     *  permissions: [{ }] //array of objects because of hasMany an using the alias defined before
     * }
     */

    return res.json(userCreated);
} catch (err) {
    // error here
}
};