Schema design // How to handle polymorphism? #3668
-
QuestionDoes anyone have examples of handling polymorphism in Prisma? I know interfaces and unions aren’t supported, but I’m looking for repos where people have figured out their own solution. Goal & backgroundI'm trying to build a Typescript + GraphQL API server that mostly handles read requests on a strongly polymorphic dataset, as well as the usual user account management stuff. I'm inexperienced with GraphQL and database design, so if it seems like I'm missing something obvious then I probably am. ExampleLet's say our dataset contains A user might request the list Desired traits of a solution
Possible solutions1. A single table with a field specifying the type, and additional nullable fields for every possible attribute.
2. Each category has its own table, separate from its parents and children. Each parent category has a type column and a nullable reference column for each of its possible children.
Wrap-upI know I can't be the first person to have this problem, so how have other people solved it? Links to repos strongly preferred. 😉 Thanks for reading. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 3 replies
-
Hey @evandjohnston 👋 Yes currently Prisma doesn't support interfaces and unions, but as per your query
You are building a GraphQL API. Why not make use of Interfaces and Unions available to you in GraphQL itself instead of creating those in the database model? The best example I would suggest is something like this. This will help you add the required interfaces in the GraphQL layer with the separations that you require. The above approach can be obtained by using an SDL first approach where you define your own schema in a Let me know if that helps! |
Beta Was this translation helpful? Give feedback.
-
Maybe I’m missing something but how would the polymorphic fields be stored in the database alongside normal prisma models? |
Beta Was this translation helpful? Give feedback.
-
I think that the Elixir library Ecto has a good page explaining how to deal with Polymorphic relationships, and some issues with the approach in frameworks/ORMs like Laravel or Rails. |
Beta Was this translation helpful? Give feedback.
Hey @evandjohnston 👋
Yes currently Prisma doesn't support interfaces and unions, but as per your query
You are building a GraphQL API. Why not make use of Interfaces and Unions available to you in GraphQL itself instead of creating those in the database model? The best example I would suggest is something like this. This will help you add the required interfaces in the GraphQL l…