简体   繁体   English

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

[英]Sequelize insert data with association meta data

My models are defined as follows 我的模型定义如下

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

在此处输入图片说明

Permissions are predefined list and store in Permission table. 权限是预定义的列表,并存储在“权限”表中。 I want to create user with all the associations at once with existing permission. 我想使用现有权限一次创建具有所有关联的用户。 How can I do this with async and await ? 我该如何使用async和await执行此操作?

I highly recommend to use an alias on your associations, on User could be something like this like this. 我强烈建议在您的关联上使用别名,在User上可能像这样。

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

An on create controller you can at once create User and UserPermission like this. 在创建时,您可以像这样立即创建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
}
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM