Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
Vinícius Santos de Pontes Avatar asked Sep 06 '25 23:09

Vinícius Santos de Pontes


2 Answers

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,
    }
  }
})
like image 130
Farista Latuconsina Avatar answered Sep 09 '25 19:09

Farista Latuconsina


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();
like image 29
hungtran273 Avatar answered Sep 09 '25 17:09

hungtran273