在同一个 sequelize 事务中创建和更新

Create and update in the same sequelize transaction

我想插入一个新行并立即更新它,所有这些都在同一个 sequelize 事务中,这可能吗?

到目前为止我的代码:

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 只有两个参数,因此 transaction 选项应该紧挨着 where 选项指出:

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