Search code examples
javascriptmysqlnestjsnestjs-typeorm

NestJS TypeORM createQueryBuilder SELECT query


I am trying to run a query

SELECT USER_CODE  
FROM USERS

using TypeORM in nestJS.

My database is MySQL and this database has a users table with the columns:

'USER_CODE', 'USER_EMAIL', 'USER_PASSWORD', 'USER_PHONE'

I've seen TypeORM official documents several times, but I don't understand them well.

//service.ts
import { InjectRepository } from '@nestjs/typeorm';
import { Injectable } from '@nestjs/common';
import { Users } from './entity/users.entity';
import { Repository } from 'typeorm';
import { UsersSignupDto } from './dto/users.signup.dto';
import { generateCode } from 'src/common/utils/code.generator';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(Users) private userRepository: Repository<Users>,
  ) {}

  async signup(body: UsersSignupDto) {
    const user = await this.userRepository
      .createQueryBuilder()
      .select('users.user_code')
      .from(users,'users')
      .where('users.user_code = :id', { id: '74EQQK' })
      .getOne();
    console.log(user);
   
}

the code returns 'null' but I checked that table's rows are not empty.

but when i tried

const user = await this.userRepository
      .createQueryBuilder()
      .where('users.user_code = :id', { id: '74EQQK' })
      .getOne();
      console.log(user);

It works.. but this query gets all information from the table.

I just want to get 'user_code' column.

How to make this work? Can someone link me the references information?


Solution

  • When using queryBuilder observe the distinction between entities and raw SQL data, and use the appropriate API methods.

    getOne (and getMany) will not work when your query returns raw SQL data rather than ORM entities. Use .getRawOne (or getRawMany) instead.