简体   繁体   中英

How to insert data to multiple tables in one db request with sequelize?

I have the following relation:

在此处输入图像描述

Association is:

  users.belongsToMany("roles", {
    through: "userRoles",
  });

When creating a user I do this:

register: async (obj, args, context, info) => {
  const PasswordHash = await bcrypt.hash(args.input.Password, 12);

  const user = db.users.create({
    ...args.input,
    Password: PasswordHash,
  });

  db.userroles.create({
    UserId: user.Id,
    RoleId: args.input.roleId,
  });
},

How to do this in one request? Right now Im doing one when creating the user and then getting the Id of the newly created user and adding a role to that user (request 2).

A followup, lets say I would have more then one junction tabel tied to users table, again how would I insert to all tables in one db request?

Create a stored proc in your MySQL DB to create both records eg

drop procedure if exists createUser
DELIMITER //
CREATE PROCEDURE createUser
(
    IN email VARCHAR(200),
    IN password BINARY(60),
    IN roleId INT
)
BEGIN
    DECLARE userId BINARY(16);

    INSERT INTO Users (Email, Password)
    VALUES (email, password);   

    # Assuming your user ID is auto-generated, pull ID of last insert
    SET userId = LAST_INSERT_ID()

    INSERT INTO UserRoles (UserId, RoleId)
    VALUES (userId, roleId);

END //

DELIMITER ;

Then you can call that stored proc using Sequelize

const { email, roleId } = args.input;
const result = await sequelize
  .query('CALL createUser (:email, :password, :roleId)', 
        {replacements: { email, password: PasswordHash, roleId }});

You can tweak to suit in terms of the relevant parameters, but you get the idea.

There is no way to create a user and add the roles at the same time unless you want to create a custom stored procedure in MySQL.

Lets try to simplify your problem. You do not know the USER ID before you create the user. Therefore it is impossible to create the role before you create the user. One way to solve this issue, is to generate the user ID in your code.

You can add an extra column in your "Users" table called GeneratedId and convert the ID column to AUTO_INCREMENT, then use a package such as https://www.npmjs.com/package/uuid to generate a unique ID before you insert the user.

Use the same generated Id to associate the role to the user (The "UserId" column in the "UserRole" table will contain the Id you generated in code).

Now you can add the user and all the associated data without waiting for the answer from the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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