How to return only some columns of a relations with Typeorm

14,942

The findOne function accepts an select: ['id', 'createdAt'] property where you can filter the fields of the outgoing relation. To explicitly select the returned fields of a joined table (using the relations property does implicitly a left join) you have to use a query builder.

await getRepository(Foo).createQueryBuilder('foo')
  .where({ id: 1})
  .select(['foo.id', 'foo.createdAt', 'bar.id', 'bar.name'])
  .leftJoin('foo.bars', 'bar')  // bar is the joined table
  .getMany();

Share:
14,942

Related videos on Youtube

Alexandre Vieira
Author by

Alexandre Vieira

I am a developer with skills in python3, javascript (With a lot of useless frameworks that i love), C ( Because, you know, legacy systems), C++ (Basically for game development), Java, and now learning Golang.

Updated on August 01, 2022

Comments

  • Alexandre Vieira
    Alexandre Vieira almost 2 years

    Ok, i'm having trouble with getting the relations with typeorm, when i run the service it returns me 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",
    
       }
    }