首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Prisma与用户模型建立关系?

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

Stack Overflow用户
提问于 2022-09-23 10:38:20
回答 1查看 59关注 0票数 0

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

下面是我的模式的一部分

代码语言:javascript
复制
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路径:

代码语言:javascript
复制
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();
}

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

我在模型注释中的@关系应该如何使在查询中包含批注成为可能?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-09-23 11:43:32

如果您想要包含这样的相关模型,您需要告诉prisma:

代码语言:javascript
复制
await prisma.comment.findmany({
  include: {
    commenter: true,
  },
})

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73826477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档