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

如何在Prisma Schema(MySQL)的Invoice模型中添加多个外键?

Prisma Schema 外键配置实现

你需要的三个外键配置核心逻辑已具备,以下是规范后的实现说明与完整代码:

  • business_id:关联Businesses模型,通过@relation指定关联字段与参照主键,配置级联更新/删除以保障业务数据一致性
  • created_by:关联Users模型的创建者,通过自定义关联名称created_by_admin区分同表的另一关联
  • client_id:关联Users模型的客户,用关联名称client与创建者关联做区分

完整Schema代码:

model Invoices {
  id                 Int        @id @default(autoincrement())
  // 关联Businesses模型的外键
  business_id        Int        @db.Int
  Businesses         Businesses @relation(fields: [business_id], references: [id], onUpdate: Cascade, onDelete: Cascade)
  // 关联Users模型的创建者(自定义关联名)
  created_by         Int        @db.Int
  created_by_admin   Users      @relation("created_by_admin", fields: [created_by], references: [id])
  // 关联Users模型的客户(自定义关联名)
  client_id          Int
  client             Users      @relation("client", fields: [client_id], references: [id])
}

// 补充必要的关联模型示例(若项目中未定义)
model Businesses {
  id         Int        @id @default(autoincrement())
  Invoices   Invoices[] // 反向关联
  // 其他业务字段
}

model Users {
  id                 Int        @id @default(autoincrement())
  created_invoices   Invoices[] @relation("created_by_admin") // 反向关联创建的发票
  client_invoices    Invoices[] @relation("client") // 反向关联作为客户的发票
  // 其他用户字段
}

关键注意点:

  1. 同一模型(Users)多次关联时,必须通过自定义关联名称区分,否则Prisma无法识别关联关系
  2. 需在对应模型中声明反向关联并匹配关联名称,才能正常使用Prisma的关联查询功能
  3. @db.Int可根据数据库类型调整,若使用默认Int类型可省略该注解

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:24:47