Search code examples
sqltypescriptormtypeorm

TypeORM select data from nested relations


Using

await this.budgetRepository.createQueryBuilder("budget")
  .leftJoinAndSelect("budget.contact", "contact")
  .leftJoinAndSelect("contact.photo", "contactPhoto")
  .getMany();

I get a list with objects like this:

Budget {
   id: 1,
   unnecessary_property1: something,
   contact: Contact {
      unnecessary_property2: something,
      photo: Photo {
         unnecessary_property3: something,
         url: "url.com"
      },
   },
}

But I want to select only the necessary properties in the nested objects (relations) and get a list of objects like this:

Budget {
   id: 1,
   contact: Contact {
      photo: Photo {
         url: "url.com"
      },
   },
}

How is that possible with TypeORM?


Solution

  • This is possible but we have to select everything manually with .select()

    await this.budgetRepository.createQueryBuilder("budget")
      .leftJoinAndSelect("budget.contact", "contact")
      .leftJoinAndSelect("contact.photo", "contactPhoto")
      .select(['budget.id', 'contactPhoto.url']
      .getMany();