@crabasa I’m also trying to figure out the best way to handle many-to-many relations in Prisma/Redwood, and wondering what approach you eventually settled on.
Setting up the explicit link table in the Prisma schema feels like the right thing to do, since it allows adding createdAt
etc. fields to the model. And as you all have written above, the Prisma docs recommend that the fields are named after the models they relate to, but the type of the field actually refers to the link table model. So we have:
model Post {
id Int @default(autoincrement()) @id
title String
categories CategoriesOnPosts[]
}
model Category {
id Int @default(autoincrement()) @id
name String
posts CategoriesOnPosts[]
}
The categories
field on the Post
model actually points to an array of CategoriesOnPosts
, not Category
. This means that when I want to get the actual categories, I need to do something like this:
const categories = post.categories().map(categoryOnPost => categoryOnPost.category)
If I had just used the implicit version, I think I could just call post.categories()
, and not have to iterate over the link table.
As you mention, Rails lets you avoid referencing the link table. Django does the same thing - you don’t need to use the link table unless you want to get the data out of it.
This seems like it could be more of a Prisma question than a Redwood one, but I’m struggling to figure out what is the best way of building the schema, the SDL, and the resolvers to enable clean references to many-to-many relations.
Does anyone feel like they have figured out a good approach to this type of relation?