Nuwan.Niroshana
Nuwan.Niroshana

Reputation: 407

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

enter image description here

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 ?

Upvotes: 0

Views: 451

Answers (1)

Ellebkey
Ellebkey

Reputation: 2301

I highly recommend to use an alias on your associations, on User could be something like this like this.

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

An on create controller you can at once create User and UserPermission like this.

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: [email protected]
     *  permissions: [{ }] //array of objects because of hasMany an using the alias defined before
     * }
     */

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

Upvotes: 1

Related Questions