I'm trying to query comments and the user who made the comments. I'm using Prisma to create the schema and Planetscale as a database.
Below you find part of my schema
model User {
id String @id @default(cuid())
name String?
email String? @unique
emailVerified DateTime?
image String?
accounts Account[]
sessions Session[]
Comment Comment[]
}
model Comment {
id String @id @default(cuid())
text String
contentId String
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
commenterId String?
commenter User? @relation(fields: [commenterId], references: [id])
}
This is my API route:
import type { NextApiRequest, NextApiResponse } from "next";
import prisma from "../../../lib/prisma";
export default async function handle(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "GET") {
return res.status(405).json({ msg: "Method not allowed" });
}
try {
const comments = await prisma.comment.findMany();
return res.status(200).json(comments);
} catch (err) {
console.error(err);
res.status(500).json({ msg: "Something went wrong." });
}
res.end();
}
The end goals is to query the comments and get an object with the commenter, so I can display name and image.
How should my @relation in the model Comment look like to make it possible to include the commenter in the query?
You need to tell prisma if you want to include a related model like this:
await prisma.comment.findmany({
include: {
commenter: true,
},
})
https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries