'Prisma schema - Create a relation field from multiple possible foreign keys (OR relation)
How to create a relation field
in prisma schema that target 2 possible relation scalar fields
?
For instance, in soccer, let's say we've got the following 2 models:
model Match {
team1Id Int
team1 Team @relation("team1", fields: [team1Id], references: [id])
team2Id Int
team2 Team @relation("team2", fields: [team2Id], references: [id])
}
model Team {
id Int @default(autoincrement()) @id
name String
matches Match[] @relation( /* What to put here ? */ ) // <----
}
What to put in the Team.matches
relation field definition in order to allow Team.matchs
to contain any match the team played from any side, as team1 or as team2 ?
Solution 1:[1]
This is not possible in Prisma right now! I created an issue in our repo for technical specifications to think about ways for improving this!
Workaround
With Prisma you always need to have a relation field on both sides per relation. This means you need to have two relation fields on Team
, one which represents the matches where the team played "as team 1", another where it played "as team 2".
model Match {
team1Id Int
team1 Team @relation("team1", fields: [team1Id], references: [id])
team2Id Int
team2 Team @relation("team2", fields: [team2Id], references: [id])
@@id([team1Id, team2Id])
}
model Team {
id Int @default(autoincrement()) @id
name String
matchesAsTeam1 Match[] @relation("team1")
matchesAsTeam2 Match[] @relation("team2")
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |