How can I add relations to the response using TypeORM query builder

69 views Asked by At

I cannot figure out how to get the relations. Might be easier to see the code. The below function works great. It gets a list of notes and adds the group array relations to each note object when the parameter is passed in. This typical TypeORM.

public async findAll(userId: string, params?: Params): Promise<NoteEntity[]> {
  return await this.notesRepository.findAll({
    where: { user: { id: userId } },
    relations: {
      groups: params
        ? !!Object.keys(params).find((key) => key === "groups")
        : false,
    },
  });
}

However I am attempting to add search. I have the below query which returns the list of notes paginated and sorted, but I cannot figure out how to get the group relations added to the response.

public async findAll(
  userId: string,
  pageOptionsDto?: PageOptionsDto,
): Promise<PageDto<NoteDto>> {
  const queryBuilder = this.dataSource.createQueryBuilder(NoteEntity, "note");

  queryBuilder
    .where("note.userId = :userId", { userId: userId })
    .orderBy("note.createdDate", pageOptionsDto.order)
    .skip(pageOptionsDto.skip)
    .take(pageOptionsDto.take);

  const itemCount = await queryBuilder.getCount();

  const { entities } = await queryBuilder.getRawAndEntities();

  const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto });

  return new PageDto(entities, pageMetaDto);
}

Any assistance would be greatly appreciated. Thanks.

0

There are 0 answers