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

如何查询Prisma关联关系并返回父对象全部字段?以获取含已审核评论的文章为例

解决Prisma查询返回文章及已审核评论的问题

嘿,这个问题很常见,我来帮你快速搞定!

你当前的查询用了select: { Comment: ... },这就相当于告诉Prisma只返回关联的Comment数据,完全忽略了Post本身的所有字段——这就是为什么你拿不到文章内容的原因。

推荐解决方案(简洁高效)

要同时获取Post的全部字段和已审核的评论,最省心的方式是用include代替select。include会自动保留主模型(Post)的所有属性,同时可以对关联的Comment添加筛选条件:

const post = await prisma.post.findUnique({
  where: { slug },
  include: {
    Comment: {
      where: { approved: true }
    }
  },
});

这样执行后,返回的post对象会包含Post的所有字段,同时附带一个Comment数组,里面只有approved: true的评论。

备选方案(手动指定字段)

如果你因为特定需求必须使用select(比如只需要Post的部分字段,但你这里需要全部字段,所以不推荐),那你需要手动列出Post的所有字段,再加上筛选后的Comment:

const post = await prisma.post.findUnique({
  where: { slug },
  select: {
    // 这里列出Post的所有字段,比如:
    id: true,
    title: true,
    content: true,
    slug: true,
    createdAt: true,
    updatedAt: true,
    // 其他你定义的Post字段...
    Comment: {
      where: { approved: true }
    }
  },
});

显然第一种用include的方式更高效,不用每次新增Post字段都修改查询语句,强烈推荐这个方案。

内容的提问来源于stack exchange,提问作者Chris Westbrook

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:23:13