Home > Net >  Create and update in the same sequelize transaction
Create and update in the same sequelize transaction

Time:03-24

I want to insert a new row and immediately update it, all within the same sequelize transaction, is this possible?

My code so far:

let transaction;
    
try {
    transaction = await dbcontext.sequelize.transaction();
    
    const newRole = await dbcontext.Role.create({
          name: "New Role"
    }, { transaction });
    
    await dbcontext.Role.update(
          {
            name: "New name",
          },
          {
            where: {
              id: newRole.id,
            },
          }, { transaction }
    );
    await transaction.commit();
    console.log("Role commited");
} catch (error) {
    console.log("Rollback in progress");
    if (transaction) {
          await transaction.rollback();
    }
    console.log(error);
}

CodePudding user response:

update has only two parameters so the transaction option should be indicated right next to the where option:

await dbcontext.Role.update(
          {
            name: "New name",
          },
          {
            where: {
              id: newRole.id,
            },
            transaction,
          }
    );
  • Related