mcclosa
mcclosa

Reputation: 1455

TypeORM createQueryBuilder where statement not respecting Enitity column name

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 AccountRepository
  .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'

Upvotes: 1

Views: 1503

Answers (1)

ᴓᴓᴓ
ᴓᴓᴓ

Reputation: 1166

It looks like you're doing the same thing as in this question:

Typeorm ignoring @column name of columns

I'm not clear if this is documented, but I think something is wrong with explicitly named PrimaryColumn() and PrimaryGeneratedColumn(). If you absolutely need the generated column, you should be able to use

@Column(name: 'account_number',
        // "serial" type is equivalent to AI in PG
        type: 'serial',
        primary: true)
accountNumber: string;

(from here: https://github.com/typeorm/typeorm/issues/1517).

Also, you don't need the ! on a primary key, it's always going to be required.

Upvotes: 1

Related Questions