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?

Upvotes: 3

Views: 7489

Answers (3)

Farista Latuconsina
Farista Latuconsina

Reputation: 343

If you're using repository pattern that you will be achieve the similar result with:

await this.budgetRepository.find({
  relations: ["contact", "contact.photo"]
  select: {
    contactfield1: true,
    contactfield2: true,
    photo: {
      phototfield1: true,
      phototfield2: true,
    }
  }
})

Upvotes: 3

hungtran273
hungtran273

Reputation: 1357

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();

Upvotes: 1

Sufiane
Sufiane

Reputation: 2206

You would have to use the .select() function and pass the given properties you want for each entity.

for your example:

const user = await createQueryBuilder("budget")
    .leftJoinAndSelect("budget.contact", "contact")
    .leftJoinAndSelect("contact.photo", "contactPhoto")
    .select([/* everything from budget */, 'contact.photo.url'....]) // added selection
    .getMany();

Upvotes: 0

Related Questions