如何使用Prisma与用户模型建立关系



我正在尝试查询评论和发表评论的用户。我正在使用Prisma创建模式和Planetscale作为数据库。

下面你可以找到我的模式的一部分


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])
}

这是我的API路线:

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();
}

最终目标是查询评论并获得带有评论的对象,这样我就可以显示名称和图像。

模型Comment中的@relationship应该是什么样子才能在查询中包含注释?

如果你想包括这样一个相关的模型,你需要告诉prisma:

await prisma.comment.findmany({
include: {
commenter: true,
},
})

https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries

最新更新