Reputation: 33
I am using prisma orm in nodejs and have the following schema (example)
model User
{
id Int @id @default(autoincrement())
answers Answer[]
}
model Product
{
id Int @id @default(autoincrement())
questions Question[]
}
model Question
{
id Int @id @default(autoincrement())
products Product[]
answers Answer[]
}
model Answer
{
id Int @id @default(autoincrement())
userId Int
user User @relation(fields: [userId], references: [id])
productId Int
product Product @relation(fields: [productId], references: [id])
questionId Int
question Question @relation(fields: [questionId], references: [id])
}
Is it possible to get a list of products with questions and with latest answer for each question?
The problem I have is, that nested includes don't respect grandparent id.
For example, in this code:
let products = await prisma.product.findMany({
include: {
questions: {
include: {
answers: true
}
}
}
})
returned answers for each question don't also belong to the product I want them to belong to.
What am I missing?
Upvotes: 0
Views: 272
Reputation: 7218
To the best of my knowledge, it's not possible to make the query you're looking for (A second layer of nested include that also respects the grandparent ID).
A possible workaround is to include the answers alongside the questions in the product
query instead of nesting it inside questions
. Then you can merge the questions and answers in the application layer (either in the backend or frontend, whichever is most appropriate).
The code would look something like this
let products = await prisma.product.findMany({
include: {
questions: true,
answers: true, // Assuming the relation field is called answers. You confirmed you accidentally forgot to mention the field in your schema.
},
});
// In Javascript/Typescript: For every product, iterate across every answer and add to the questions array.
This workaround should work reasonably well provided the number of products/answers isn't incredibly large.
Upvotes: 1