You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Prisma中设置Comment模型关联,实现评论及评论者查询?

解决方法

1. Schema调整(可选但推荐)

你的Schema里的关系定义其实已经正确了,不过为了贴合Prisma的命名惯例,避免潜在的关系歧义,建议做一点小优化:

  • 将User模型里的Comment字段改成小写复数comments(Prisma默认用复数命名反向关联)
  • 给@relation加上明确的name参数,让关系逻辑更清晰

调整后的Schema代码:

model User {
  id            String    @id @default(cuid())
  name          String?
  email         String?   @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  comments      Comment[] @relation(name: "UserComments")
}

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], name: "UserComments")
}

2. 修改查询逻辑,关联加载评论者

问题的核心不是Schema的关系设置错误,而是你当前的查询没有加载关联的评论者数据。只需要在findMany()里加上include选项,就能把评论者的信息一起查出来:

修改后的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({
      include: {
        commenter: {
          select: { // 可选:只返回需要的字段,减少数据传输量
            id: true,
            name: true,
            image: true
          }
        }
      }
    });
    return res.status(200).json(comments);
  } catch (err) {
    console.error(err);
    res.status(500).json({ msg: "Something went wrong." });
  }
}

额外说明

  • 如果允许匿名评论(commenterId可为null),返回的commenter字段会是null,前端需要处理这种情况
  • 用select指定返回字段比加载全部用户数据更高效,适合只需要姓名和头像的场景

内容的提问来源于stack exchange,提问作者Mathias Riis Sorensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:35:23