Search code examples
mysqlnode.jsnestjsquery-buildertypeorm

TypeOrm - NestJS using queryBuilder


I have this db schema in mysql:

     users_tbl
     --------------------------------------------
     id        |  first_name         | last_name
     --------------------------------------------
     1         |  Jon                | Doe
     2         |  Mark               | Smith


     address_tbl
     ------------------------------------------------------------
     id        |  address            | city             | user_id
     ------------------------------------------------------------
     1         |  some address       | some city        | 1

Then, I wanted to use TypeOrm's queryBuilder inorder to get the address of Jon Doe.

My raw sql query: SELECT users.first_name, users.last_name, address.address, address.city FROM users INNER JOIN address ON address.user_id=users.id

My TypeOrm queryBuilder:

const users = await this.userRepo
      .createQueryBuilder('users')
      .select('users.first_name', 'fName')
      .addSelect('users.last_name', 'lName')
      .addSelect('adr.address', 'address')
      .addSelect('adr.city', 'city')
      .innerJoin('address', 'adr', 'adr.user_id=users.id')
      .getMany();
return users;

There doesn't seem to have any error as I am able to run a GET request. However, it returns an empty object. In my console, NestJS (or TypeORM) logs the generated mysql query. Here it is:

SELECT adr.city AS city, adr.country AS country, adr.id AS adr_id, users.first_name AS fName, users.last_name AS lName FROM users users INNER JOIN address adr ON adr.user_id = users.id

I copied and pasted it to perform a manual query in phpmyadmin. And the query seems to work, and gives me the expected output. Am I missing something in my code, or is this some TypeORM limitation?


Solution

  • Try using getRawMany instead of getMany as follows -

    return await this.userRepo
          .createQueryBuilder('users')
          .select('users.first_name', 'fName')
          .addSelect('users.last_name', 'lName')
          .addSelect('adr.address', 'address')
          .addSelect('adr.city', 'city')
          .innerJoin('address', 'adr', 'adr.user_id=users.id')
          .printSql() 
          .getRawMany();