P
Prisma6mo ago
Markigno

multiple relation with same field

let's assume i want to use the same field to create a relation to different tables, is it possible? I'm thinking something like this LinkTable{ id String @id @default(uuid()) idLink String linkedTable String //this will assume value "TABLE1" or "TABLE2" table1 Table1 @relation(fields: [linkedTable ], references: [id]) table2 Table2 @relation(fields: [linkedTable ], references: [id]) } Table1{ id String @id @default(uuid()) ... } Table2{ id String @id @default(uuid()) }
1 Reply
Prisma AI Help
Prisma AI Help6mo ago
You selected the bot's instantaneous insights. Let me compile your answer right away! No, Prisma does not currently support using a single field to create polymorphic relations (i.e., a relation where the same field can reference different tables based on another field's value, like your example with linkedTable and idLink). Prisma requires that each relation field references a specific model, and you cannot have one field (e.g., idLink) that conditionally relates to multiple tables. The only supported workaround is to create separate fields for each possible relation, such as table1Id and table2Id, and then define separate relations for each. This is a known limitation, and there are open feature requests for true polymorphic relations, but as of now, you must use multiple columns—one for each referenced table. See the official answers and discussions for confirmation of this limitation and the suggested workaround: - "At the moment, it’s not possible. Prisma needs to know in advance the table referenced by the foreign key. The only workaround is to have multiple columns for each referencing table." Multiple models for one column in case of multiple foreign keys - "You would need to define two fields a_link_id and b_link_id and then you can filter on them. Two relations cannot have the same fields." Is that possible to relation to different model with a field by some other field value? - Related feature requests are still open and not yet implemented Polimorph Relation Schema So, your proposed schema is not possible with Prisma at this time. You must use separate fields for each relation. ✅ Great, thanks for letting us know that this solved your question!

Did you find this page helpful?