Search code examples
databaseexpresssequelize.jsassociations

Sequelize, create new User and assign already created roles in one query?


Is it possible to create a user and set roles in sequelize like the code bellow or somehow without creating the user first and then setting the roles?

User.create({name: ’test’, password:’test’, roles:[1,2] })

Given the role ids 1,2


Solution

  • You can only create roles along with a user using one call. To assign existing roles to a user you need two calls:

    1. to create a user
    2. assign roles to the created user (calling a special method of the created user).

    Anyway even if such a possibility exists technically it turns into two SQL queries. Don't forget to indicate the same transaction in both calls (1 and 2).