typeorm / typeorm

ORM for TypeScript and JavaScript. Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, SAP Hana, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
http://typeorm.io
MIT License
34.24k stars 6.31k forks source link

Querybuilder not respecting Enitity column name #8908

Open AaronMcCloskey opened 2 years ago

AaronMcCloskey commented 2 years ago

Issue Description

I have a pre-existing database table that has a column with a name of account_number, however, I wanted to reference this column in my code as accountNumber instead.

I have the following entity where I set the column name for the property type of accountNumber to be account_number...

import { ObjectType, Field } from 'type-graphql';
import { Entity, PrimaryGeneratedColumn, Column, BaseEntity } from 'typeorm';

@ObjectType()
@Entity({ database: 'main', name: 'account' })
class Account extends BaseEntity {
  @Field(() => String)
  @Column({ name: 'account_number' })
  @PrimaryGeneratedColumn()
  accountNumber!: string;

  @Field(() => String)
  @Column()
  organisation!: string;
}

export default Account;

This is the query builder that I am having an issue with

await getConnection('main')
  .getRepository(Account)
  .createQueryBuilder('a')
  .where('a.`account_number` = :accountNumber', { accountNumber: "abc123" })
  .getOne();

Expected Behavior

Query to resolve using the account_number column as is stated in the Column decorator.

SELECT `a`.`account_number` AS `a_accountNumber`, 
`a`.`organisation` AS `a_organisation` 
FROM `main`.`account` `a` 
WHERE a.`account_number` = 'abc123'

Actual Behavior

However, it seems to want to use accountNumber instead of account_number even though I have set it as so in the Entity

SELECT `a`.`accountNumber` AS `a_accountNumber`, 
`a`.`organisation` AS `a_organisation` 
FROM `main`.`account` `a` 
WHERE a.`account_number` = 'abc123'

My Environment

Dependency Version
Operating System macOS Catalina
Node.js version v16.13.0
Typescript version 4.5.4
TypeORM version 0.2.38

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql no
aurora-postgres no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql yes
nativescript no
oracle no
postgres no
react-native no
sap no
spanner no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

Are you willing to resolve this issue by submitting a Pull Request?

AlexMesser commented 2 years ago

You should put a name into @PrimaryGeneratedColumn() and remove the @Column() decorator. Here how it should look:

@Field(() => String)
@PrimaryGeneratedColumn({ name: 'account_number' })
accountNumber!: string;
trim21 commented 1 month ago

This is affected by how you create createQueryBuilder

With createQueryBuilder('t'), and you can use .where('t.accountNumber ...') for column account_number, but if you use createQueryBuilder(), then you have to use .where('account_number...')