Creating this topic to capture some advice from the Core team on how to model many-to-many (m:n) relationships in Redwood apps.
I have a schema that has Posts and Categories. I am trying to figure out how to:
- connect these two models in a m:n relationship
- define metadata for the connection between a Post and a Category
The example blog app shows us how to do (1) but not how to do (2):
model Post {
id Int @id @default(autoincrement())
title String
slug String @unique
author String
body String
image String?
tags Tag[]
postedAt DateTime?
}
model Tag {
id Int @id @default(autoincrement())
name String @unique
posts Post[]
}
For folks who are familiar with Rails (and ActiveRecord) what I’m trying to accomplish is similar to the :has_many :through. I need an intermediate model to store metadata on, but I still want the convenience of access Categories through a Post and Posts through a Category.
So based on the Prisma documentation for this use case, I built a model that looks like this:
model Post {
id Int @default(autoincrement()) @id
title String
categories Category[] @relation(references: [id])
}
model Category {
id Int @default(autoincrement()) @id
name String
posts Post[] @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])
}
But when I try to build a migration or generate the Prisma client, the schema fails to validate.
Setting aside errors related to Prisma or the difference between the preview
and beta
release, I would like to know if there is a recommended Redwood Way™️ to
- Model this kind of association
- Construct
services
to CRUD these associations