Prisma - 使用时仅包含 return 子对象字段

Prisma - When use include return only subobject fields

我写了这个函数来过滤 table building 结束可选我可以将 Prisma.BuildingInclude 对象传递给 return 一个或多个子对象。

async describeEntity(filter: Filter, include?: Prisma.BuildingInclude): Promise<CCResponse> {
  try {
    const entity = await this.prisma.building.findMany({
      where: this.queryCondition(filter),
      include,
    });

    return new CCResponse('OK', entity);
  }
  catch (err) {
    console.log(err);
    return new CCResponse('INTERNAL_ERROR', this.content['GeneralError']);
  }
}

问题是,如果我将 include 参数传递给 prisma 响应,我也有 building 的字段。当存在 include 参数时,如何仅 return 子对象字段?

您可以将 include 条件替换为 select 条件来解决此问题。

例如,要查找具有完全相同 where 条件的许多 building 记录,但只查找 return 所需的关系子对象字段,查询可能如下所示

 const entity = await this.prisma.building.findMany({
      where: this.queryCondition(filter),
      select: {
            relationSubObjectOne: true,  //change relationSubObjectOne to appropriate relation name..
            relationSubObjectTwo: true,  //change relationSubObjectTwo to appropriate relation name..
            // ... other fields/subobjects you might be interested in.
        },
    });

您可以在 Prisma 文档中 Select fields 文章的 包含关系和 select 关系字段 小节中了解更多相关信息。