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

Prisma与TypeGraphQL多对多关联查询无结果问题求助

多对多关联查询无结果的修复方案

你的问题核心出在Categories Resolver的projects字段解析器里,存在三个关键错误,导致查询不到关联项目:

错误点分析

  1. Root参数类型错误:为Category实体写的字段解析器,@Root参数却用了Project类型,实际应该是Category,这会导致拿错ID去查询。
  2. 查询条件方向搞反:要找属于当前分类的项目,应该用categoryId匹配分类ID,而不是用projectId。
  3. 返回类型不匹配:FieldResolver声明返回[Project],但实际返回的是中间表CategoryToProject数组,前端需要的是Project实体数据,不是中间表记录。

修复后的Categories Resolver代码

@Resolver(Category) // 确保Resolver装饰器参数是Category
export class GetCategoriesResolver {
  @FieldResolver(() => [Project])
  async projects(
    @Root() category: Category, // 修正Root参数类型为Category
    @Ctx() { prisma }: Context
  ): Promise<Project[]> { // 修正返回类型为Project数组
    // 查询中间表并关联Project实体
    const categoryProjects = await prisma.categoryToProject.findMany({
      where: {
        categoryId: category.id, // 修正查询条件为categoryId
      },
      include: {
        project: true // 关联查询对应的Project
      }
    });
    // 提取Project实体返回
    return categoryProjects.map(item => item.project);
  }

  @Query(() => [Category])
  async getCategories(@Ctx() { prisma }: Context): Promise<Category[]> {
    return await prisma.category.findMany({
      include: {
        projects: true,
      },
    });
  }
}

额外验证点

  • 确认Resolver类上的@Resolver()装饰器参数是Category,而非其他实体。
  • 检查Prisma生成的类型定义,确保Category和Project类型已正确导入。

修改后执行查询,就能正确返回分类下关联的项目数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 07:24:12