Prisma 使用相同模型的 1-1 和 1-n 关系

Prisma using 1-1 and 1-n relation with same model

在这种情况下,一个 Product 有许多 Image,还有一张主图Image.

但是当我运行 prisma format,抛出错误:

error: Error validating field `image` in model `Product`: The relation field `image` on Model `Product` is missing an opposite relation field on the model `ProductImage`. Either run `prisma format` or add it manually.

我的schema.prisma:

model ProductImage {
  id         String   @id @default(uuid()) @db.VarChar(36)
  product_id String
  product    Product  @relation(fields: [product_id], references: [id])
  src        String   @db.VarChar(255)
  created_at DateTime @default(now())
  updated_at DateTime @default(now()) @updatedAt

  @@map("product_image")
}

model Product {
  id         String         @id @default(uuid()) @db.VarChar(36)
  image_id   String
  image      ProductImage   @relation(name: "main_image", fields: [image_id], references: [id])
  images     ProductImage[]
  slug       String         @unique(map: "slug") @db.VarChar(255)
  title      String         @db.VarChar(255)
  created_at DateTime       @default(now())
  updated_at DateTime       @default(now()) @updatedAt

  @@map("product")
}

这个模型应该可以解决问题:

model Product {
  id         String         @id @default(uuid()) @db.VarChar(36)
  image_id   String         @unique
  // image   ProductImage   @relation(name: "main_image", fields: [image_id], references: [id])
  image      ProductImage   @relation(name: "main_image", fields: [image_id], references: [id], onDelete: NoAction, onUpdate: NoAction)
  images     ProductImage[]
  slug       String         @unique(map: "slug") @db.VarChar(255)
  title      String         @db.VarChar(255)
  created_at DateTime       @default(now())
  updated_at DateTime       @default(now()) @updatedAt

  @@map("product")
}

model ProductImage {
  id                 String    @id @default(uuid()) @db.VarChar(36)
  src                String    @db.VarChar(255)
  created_at         DateTime  @default(now())
  updated_at         DateTime  @default(now()) @updatedAt
  product_id         String
  product            Product   @relation(fields: [product_id], references: [id])
  product_main_image Product[] @relation("main_image")

  @@map("product_image")
}

这些 references 与 Prisma 模式中的关系应该会有所帮助。