在Prisma中为复合ID模型添加一对多关联遇错求助
解决Prisma复合ID模型的一对多关联问题
你的问题出在关联复合主键时的字段引用错误:UserPlantSpeciesInventoried的复合ID是由userId和plantSpeciesId两个独立字段组成的,并非自动生成名为userId_plantSpeciesId的合并字段,直接引用这个不存在的字段自然会报错。
正确的做法是在InventoryReadyByDate中添加与复合ID对应的两个外键字段,再通过这两个字段建立关联:
修改后的完整模型代码
UserPlantSpeciesInventoried(无需修改,保持原结构)
model UserPlantSpeciesInventoried { userId String user User @relation("user", fields: [userId], references: [id]) plantSpeciesId String plantSpecies PlantSpecies @relation("plantSpecies", fields: [plantSpeciesId], references: [id]) inventoryReadyByDate InventoryReadyByDate[] @@id([userId, plantSpeciesId]) }
InventoryReadyByDate(关键修改部分)
model InventoryReadyByDate { id String @id @default(cuid()) // 添加对应复合ID的两个外键字段,类型与关联模型一致 userId String plantSpeciesId String // 关联配置:fields指定当前模型的外键字段数组,references指定关联模型的复合ID字段数组 userPlantSpeciesInventoried UserPlantSpeciesInventoried @relation(fields: [userId, plantSpeciesId], references: [userId, plantSpeciesId]) quantity Int @default(0) dateReadyBy DateTime }
核心逻辑说明
- 关联复合主键的模型时,外键必须是与复合ID字段数量、类型完全匹配的字段组合,不能用单个字段去引用不存在的合并字段。
- Prisma会通过这两个外键字段,自动建立与
UserPlantSpeciesInventoried复合ID的关联关系,同时保留原有的一对多映射(一个用户-植物组合对应多个准备日期记录)。
内容的提问来源于stack exchange,提问作者Mason Stevens
相关产品推荐
相关产品推荐

