Prisma和mongodb可选唯一字段为空时抛出“唯一约束”错误

rlcwz9us  于 2023-01-08  发布在  Go
关注(0)|答案(1)|浏览(290)

我在prisma架构中有以下模型:

model Order {
  id                  String   @id @default(auto()) @map("_id") @db.ObjectId
  customer            User     @relation(fields: [customerId], references: [id])
  customerId          String   @db.ObjectId 
  products            Json
  status              String   @default("pending")
  paymentMethod       String?
  pixPayment          Payment? @relation(name: "pixPayment", fields: [pixPaymentId], references: [id])
  pixPaymentId        String?  @unique @db.ObjectId
  creditCardPayment   Payment? @relation(name: "creditCardPayment", fields: [creditCardPaymentId], references: [id])
  creditCardPaymentId String?  @unique @db.ObjectId
  boletoPayment       Payment? @relation(name: "boletoPayment", fields: [boletoPaymentId], references: [id])
  boletoPaymentId     String?  @unique @db.ObjectId
  total               Float
  createdAt           DateTime @default(now())

  @@map("Orders")
}

model Payment {
  id                     String    @id @default(auto()) @map("_id") @db.ObjectId
  paymentId              Int
  amount                 Float
  paymentMethod          String
  customer               User      @relation(fields: [customerId], references: [id])
  customerId             String    @db.ObjectId
  payer                  Json?
  installments           Int       @default(1)
  status                 String    @default("pending")
  dateOfExpiration       DateTime
  dateApproved           DateTime?
  barcode                String?
  boletoUrl              String?
  pixQrCode              String?
  pixQrCodeBase64        String?
  lastFourDigitsCard     String?
  cardHolder             Json?
  createdAt              DateTime  @default(now())
  pixPaymentOrder        Order?    @relation("pixPayment")
  creditCardPaymentOrder Order?    @relation("creditCardPayment")
  boletoPaymentOrder     Order?    @relation("boletoPayment")

  @@map("Payments")
}

我试图创建一个订单文档与必填字段(产品,总,customerId),它的作品,但只有一次,如果我尝试创建另一个订单,我得到错误:“唯一约束在约束上失败:pixPaymentId是一个唯一的可选字段,在这种情况下,我不会传递它.订单创建代码:

const order = await prisma.order.create({
            data: {
                products,
                total,
                customerId: userId
            },
            select: {
                id: true
            }
        });

我希望可以创建多个订单文档,而不使用pixPaymentId,因为它是一个可选字段,但我得到了唯一约束错误。

oprakyz7

oprakyz71#

Prisma尚不支持unique and nullable功能。
对于这种情况,只能声明为nullable,手工处理唯一性,实现unique and soft delete时也会出现同样的问题。
他们不支持它的原因是因为大多数数据库拒绝唯一约束上的重复NULL。
遵循以下讨论:https://github.com/prisma/prisma/issues/3387

相关问题