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

Node.js Apollo Server调用Prisma查询关联数据返回null如何解决

问题解决方案

问题根因

Prisma 默认采用懒加载策略,查询主模型时不会主动拉取关联的嵌套模型数据,你当前的查询仅拉取了 Participant 表的基础字段,没有加载关联的 User、Propose、Product 数据,因此返回的关联字段为 null。

解决方案1:查询时直接指定关联加载(性能最优,推荐)

直接在 findMany 方法中添加 include 参数,声明需要加载的关联字段,嵌套关联需要逐层声明:
修改你的 Query resolver 代码如下:

export default {
  Query: {
    seeParticipant: async (_, __, { loggedInUser }) => {
      try {
        const participants = await client.participant.findMany({
          where: {
            userId: loggedInUser.id,
          },
          // 新增include声明加载关联数据
          include: {
            user: true,
            propose: {
              include: {
                product: true
              }
            }
          }
        });
        return {
          ok: true,
          participants,
        };
      } catch (e) {
        return {
          ok: false,
          error: e.message,
        };
      }
    },
  },
};

该方案通过一次SQL关联查询就能拿到所有需要的数据,不存在额外查询开销,适合查询逻辑固定的场景。

解决方案2:编写字段级解析器(灵活复用)

如果 Participant 类型的 user、propose 字段需要在多个查询中复用,可以为这两个字段单独编写解析器,每次查询到Participant对象时会自动触发关联数据加载:
在你的 resolver 文件中追加 Participant 类型的解析逻辑:

export default {
  Query: {
    seeParticipant: async (_, __, { loggedInUser }) => {
      try {
        const participants = await client.participant.findMany({
          where: {
            userId: loggedInUser.id,
          },
        });
        return {
          ok: true,
          participants,
        };
      } catch (e) {
        return {
          ok: false,
          error: e.message,
        };
      }
    },
  },
  // 新增字段级解析器
  Participant: {
    user: async (parent, _, { client }) => {
      return client.user.findUnique({
        where: { id: parent.userId }
      });
    },
    propose: async (parent, _, { client }) => {
      return client.propose.findUnique({
        where: { id: parent.proposeId },
        include: { product: true }
      });
    }
  }
};

该方案灵活性更高,但如果单次查询返回多条Participant数据,会触发N+1查询问题,对性能敏感的场景建议优先使用第一种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:48:01