简体   繁体   English

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

[英]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?我想插入一个新行并立即更新它,所有这些都在同一个 sequelize 事务中,这可能吗?

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: update只有两个参数,所以transaction选项应该在where选项旁边显示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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