title: Polymorphism in Prisma Schema - Best practices?
body: <p>This is more a design question than a coding question. Suppose the following schema:</p>
  <pre><code>// schema.prisma
  // Solution 1
  
  model Entity {
    id    Int          @id @default(autoincrement())
    attrs EntityAttr[] 
  }
  
  model EntityAttr {
    id       Int         @id @default(autoincrement())
    value    Json        // or String, doesnt matter much here
                         // the point is I need to attach info on the
                         // join table of this relation
    attr     Attr        @relation(fields: [attrId], references: [id])
    entity   Entity      @relation(fields: [entityId], references: [id])
  
    entityId Int
    attrId   Int
  
    @@unique([entityId, attrId])
  }
  
  model Attr {
    id       Int          @id @default(autoincrement())
    entities EntityAttr[]   
  }
  </code></pre>
  <pre><code>// Solution 2
  model Entity {
    id          Int          @id @default(autoincrement())
    dateAttrs   DateAttr[]
    recordAttrs RecordAttr[]
    // ... this pattern could continue for more Attr-like models
  }
  
  model DateAttr {
    id     Int       @id @default(autoincrement())
    name   String
    entity Entity    @relation(fields: [entityId], references: [id])
    value  DateTime  // Stronger typing in generated code
  }
  
  model RecordAttr {
    // ... define another Entity @relation(...)
    name   String
    value  String
    // ...
  }
  
  // ... and so on
  </code></pre>
  <p><code>Please note that the schema might not be 100% complete or accurate. It is mainly to get the point across.</code></p>
  <p>Solution 1 has its merits where redundancy and the number of tables in the database is reduced significantly (depending on the number of <code>Attr</code>s). Its downfall comes as confusing queries<code>*</code>, possible case-specific type casting and no code-completion for the <code>value</code> field for each <code>Attr</code>-like model.</p>
  <blockquote>
  <p><code>*</code> by confusing, I mean that the option for simplified m-n queries in <code>prisma</code> is functionally disabled when using a custom join table (e.g. <code>EntityAttr</code>)</p>
  </blockquote>
  <p>Solution 2 has its merits where the generated code results in more strongly typed code generation for the <code>value</code> field, however it falls in the number of generated tables (I don't actually know if more tables is a good thing or a bad thing, all I think is that if you have similar values, they ought to be in the same table).</p>
  <p><strong>What would you do in my shoes?</strong></p>