th3g3ntl3man
th3g3ntl3man

Reputation: 2106

Prisma - When use include return only subobject fields

I wrote this function that filter the table building end optionally I can pass a Prisma.BuildingInclude object to return one ore more subobject.

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']);
  }
}

The problem is that if I pass the include parameter, into prisma response I have also the fields of the building. How can I return only the subobject fields when the include parameter is present?

Upvotes: 1

Views: 2025

Answers (1)

Tasin Ishmam
Tasin Ishmam

Reputation: 7218

You can replace the include condition with a select condition to solve this.

For example, to find many building records with the exact same where condition, but to only return the desired relation sub-object fields, a query might look like this

 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.
        },
    });

You can learn more about this in the Include relations and select relation fields subsection of the Select fields article in the Prisma Docs.

Upvotes: 2

Related Questions