代码之家  ›  专栏  ›  技术社区  ›  Eduardo Pacheco

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

  •  0
  • Eduardo Pacheco  · 技术社区  · 3 年前

    我想在同一个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);
    }
    
    0 回复  |  直到 3 年前
        1
  •  1
  •   Anatoly    3 年前

    update 只有两个参数,所以 transaction 选项应显示在屏幕旁边 where 选项:

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