Prisma 错误:由于写入冲突或死锁,事务失败。请重试您的交易

问题描述 投票:0回答:1

我正在后端应用程序中使用 Prisma。我想管理每个角色和用户的导航项。这是我的数据库模型和删除旧导航以更新的语句。

model Navigation {
  id        String       @id @default(cuid())
  createdAt DateTime?    @default(now())
  updatedAt DateTime?    @default(now()) @updatedAt
  name      String?
  title     String?
  subtitle  String?
  type      String?
  icon      String?
  link      String?
  userId    String?
  order     Int?
  roleId    String?
  parentId  String?
  children  Navigation[] @relation(name: "Navigation_children")
  featureId String?
  user      User?        @relation(name: "User_navigations", fields: [userId], references: [id])
  parent    Navigation?  @relation(name: "Navigation_children", fields: [parentId], references: [id], onDelete: NoAction, onUpdate: NoAction)
}
    await  this.navigation.deleteMany({
        where: {
          userId: userId,
          parentId: {
            not: null,
          },
        },
      })
    await  this.navigation.deleteMany({
        where: {
          userId: userId,
          parentId: null
        },
      })

我的导航项只有 2 层,所以我想我可以使用上述命令删除所有导航项。但我得到了错误:

无效的

prisma.navigation.deleteMany()
调用:
由于写入冲突或死锁,事务失败。请重试您的交易

如何解决这个错误?

如何仅使用 1 个命令删除所有不必要的导航项?

谢谢你。

javascript sql sql-server prisma
1个回答
0
投票

我解决了我的问题,所以我会分享。

首先,我分离了孩子以避免外键约束问题。然后删除记录。

这是我的代码。

    // First, detach children to avoid foreign key constraint issues.
    await this.navigation.updateMany({
      where: {
        userId: userId,
        parent: {
          isNot: null,
        },
      },
      data: {
        parentId: null,
      },
    });

    // Then, delete the records.
    await this.navigation.deleteMany({
      where: {
        userId: userId,
      },
    });
© www.soinside.com 2019 - 2024. All rights reserved.