Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
740 views
in Technique[技术] by (71.8m points)

mysql - 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?

question from:https://stackoverflow.com/questions/65870541/typeorm-nestjs-using-querybuilder

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...