我从PARAMS获得数组中的ID,我应该更新具有特定ID的记录的凭据.问题是,如果没有找到记录,则事务应该回滚.这就是我所做的:

     await this.prisma.$transaction( async () => {
        for(let id of ids) {
          // get category from db
          const category = await this.prisma.category.findFirst({
            where: { id: +id, deleted_at: null },
          });

          // check if exists
          if (!category) {
            throw new BadRequestException({
                status: 400,
                error: true,
                message: 'Category is not found',
            });
          }
          // soft delete from db
          await this.prisma.category.update({
            where: { id: +id },
            data: { deleted_at: new Date() },
          });
        }
      })

即使我在找不到记录时抛出Error,其他记录也会被更新.

我做的第二种方式是:

     await this.prisma.$transaction(
          ids.map(id => this.prisma.category.update({
                where: { id: +id },
                data: { deleted_at: new Date() },
          })
      ));

在这种情况下,如果没有找到记录,我会得到这样的错误:

无效的this.prisma.category.update() Invoocation in\n/files/src/category/category.service.ts:177:46\n\n 174}\n 175\n 176正在等待this.prisma.$Transaction(\n→177 ids.map(id=>this.prisma.Category y.UPDATE)(\n操作失败,因为它依赖于一个或多个所需但未找到的记录.找不到要更新的记录

但在这种情况下,其他记录也在更新! 在这种情况下我应该怎么做?

如有任何帮助,我们不胜感激:)

推荐答案

Interactive Transactions

传递到此异步函数的第一个参数是Prisma客户端的一个实例.下面,我们将该实例命名为tx.Any Prisma call invoked on this 100 instance is encapsulated into the transaction.

您需要在传递给函数的客户端实例上进行调用.

例如

await this.prisma.$transaction(async (tx) => {
  const category = await tx.category.findFirst({ // ? `tx`, not `this.prisma`
    where: { id: +id, deleted_at: null },
  });

  // etc
});

Typescript相关问答推荐

TypScript如何在 struct 上定义基元类型?

React router 6.22.3不只是在生产模式下显示,为什么?

类型{...}的TypeScript参数不能赋给类型为never的参数''

键集分页顺序/时间戳上的筛选器,精度不相同

TypeScript:在作为参数传递给另一个函数的记录中对函数的参数实现类型约束

material 表不渲染任何数据

TypeScrip:逐个 case Select 退出noUncheck kedIndexedAccess

接口中函数的条件参数

如何将定义模型(在Vue 3.4中)用于输入以外的其他用途

RXJS将对键盘/鼠标点击组合做出react

有没有可能创建一种类型,强制在TypeScrip中返回`tyPeof`语句?

带投掷的收窄类型

类型实例化过深,可能是无限的&TypeScrip中的TupleUnion错误

VITEST警告:当前的测试运行器不支持After Each/teardown挂钩

如何在TypeScrip中使用数组作为字符串的封闭列表?

仅当类型为联合类型时映射属性类型

如何避免TS2322;类型any不可分配给类型never;使用索引访问时

为什么 TypeScript 类型条件会影响其分支的结果?

基于泛型类型的条件类型,具有条目属性判断

redux-toolkit、createAsyncThunk 错误