简体   繁体   中英

Create and update in the same sequelize transaction

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

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

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