Many-to-Many Relationships the Redwood Way™️

Couldn’t you do something like this? (i.e. change the relation type in Post and Category?)

model Post {
  id         Int        @default(autoincrement()) @id
  title      String
  categories CategoriesOnPost[] @relation(references: [id])
}

model Category {
  id    Int    @default(autoincrement()) @id
  name  String
  posts CategoriesOnPost[] @relation(references: [id])
}

model CategoriesOnPosts {
  post       Post     @relation(fields: [postId], references: [id])
  // relation scalar field (used in the `@relation` attribute above)
  postId     Int
  category   Category @relation(fields: [categoryId], references: [id])
  // relation scalar field (used in the `@relation` attribute above)
  categoryId Int
  createdAt  DateTime @default(now())

  @@id([postId, categoryId])
}

This is how you used to make through tables with extra data in Django (I believe, it’s been a while).

I remember doing something like this for a recipe app, translated to Prisma:

model Product {
  id Int @id
  name String
  ingredients Ingredient[] @relation
}

model Recipe {
  id Int @id
  name String
  ingredients Ingredient[] @relation
}

model Ingredient {
  recipe Recipe @relation
  product Product @relation
  amount Int
}

Ingredient is now basically a through table for Recipes and Products.

(My hunch is that this is what they meant to write in the Prisma doc, but they forgot to replace the related models after copy-pasting!)

1 Like