You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Prisma一对多自关联创建报错求助:缺失反向关联字段

解决Prisma自关联一对多模型的P1012错误

你遇到的P1012错误是因为自关联关系必须定义双向字段——当前只声明了主SKU指向变体的variants字段,但缺少变体指向主SKU的反向关联字段。

要实现"主SKU关联多个尺码/属性变体"的需求,需要在Shoe模型中添加一个可选的父级字段,用来关联到对应的主SKU。修正后的模型如下:

model Shoe {
  id            Int      @id @default(autoincrement())
  createdAt     DateTime @default(now())
  updatedAt     DateTime @updatedAt
  sku           String   @unique
  model         String   @db.VarChar(50)
  description   String   @db.VarChar(256)
  image         String   @db.VarChar(256)
  category      String   @db.VarChar(256)
  gender        Gender
  size          String
  stock         Int
  // 主SKU关联的所有变体
  variants      Shoe[]   @relation("ShoeVariants", references: [id])
  // 变体对应的主SKU(可选,主SKU的该字段为null)
  parentShoe    Shoe?    @relation("ShoeVariants", fields: [parentShoeId], references: [id])
  parentShoeId  Int?
}

enum Gender {
  Men
  Women
}

关键说明:

  • parentShoe:可选字段,变体通过它指向对应的主SKU,主SKU的该字段值为null
  • parentShoeId:数据库层面的外键字段,用来存储主SKU的id
  • @relation("ShoeVariants"):指定统一的关系名称,确保双向字段关联的是同一个关系

这样设计后,你就可以通过主SKU的variants字段获取所有关联的变体,也可以通过变体的parentShoe字段找到对应的主SKU,完全匹配你的需求。

内容的提问来源于stack exchange,提问作者AlanJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 22:27:19