Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return only some columns of a relations with Typeorm

Ok, I'm having trouble with getting the relations with typeorm. When I run the service it returns all the data from the relation, and I want only specific fields, like id and name.

Here's my code:

async findById(id: string): Promise<UsersUseOfferHistoric> {
return await this.repository.findOne({
  where: { id },
  relations: ['userId', 'offerId'],
  });
}

Here's the JSON output:

{
"id": "da0fd04e-17c6-4412-b342-a4361d191468",
"createdAt": "2020-01-07T19:48:30.840Z",
"userId": {
    "id": "bdc00227-569f-44b5-9bdd-c8de03661ebd",
    "name": "Alexandre Vieira",
    "cpf": "10443771430",
    "email": "[email protected]",
    "password": "asjdsifjdsfasf",
    "imagePath": "/me.png",
    "active": true,
    "lastLogin": "2020-01-07T19:40:26.850Z",
    "createdAt": "2020-01-07T19:40:26.850Z",
    "updatedAt": "2020-01-07T19:40:26.850Z"
},
"offerId": {
    "id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779",
    "offerDrescription": "Nova oferta top",
    "discountCoupon": " Desconto top",
    "discountValidity": "2020-01-07T14:18:19.803Z",
    "discountPercentage": 20,
    "discountQuantityLimit": 50,
    "createdAt": "2020-01-07T19:45:33.589Z",
    "updatedAt": "2020-01-07T19:45:33.589Z"
   }
}

Here's the output I want:

{
"id": "da0fd04e-17c6-4412-b342-a4361d191468",
"createdAt": "2020-01-07T19:48:30.840Z",
"userId": {
    "id": "bdc00227-569f-44b5-9bdd-c8de03661ebd",
    "name": "Alexandre Vieira",
   
},
"offerId": {
    "id": "e399560c-d2c2-4f4e-b2b1-94cae3af3779",
    "offerDrescription": "Nova oferta top",
   
   }
}
like image 208
Alexandre Vieira Avatar asked Sep 13 '25 15:09

Alexandre Vieira


1 Answers

You can do it like this if you rather use the repository API instead of the queryBuilder

return await this.repository.findOne({
  where: { id },
  select: {
    userId: {
      id: true,
      name: true
    },
    offerId: {
      id: true,
      offerDrescription: true
    }
  },
  relations: {
    userId: true,
    offerId: true,
  }
});
like image 165
Sim0rn Avatar answered Sep 15 '25 05:09

Sim0rn