Sven Peeters
Sven Peeters

Reputation: 41

Duplicate column name with TypeORM in Nestjs

We have 2 entities: EstateIntegrationEntity and EstateEntity

When we try to use .findOne on the estateIntegrationRepository we get the following error:

[Nest] 5537   - 10/01/2020, 8:37:55 AM
[ExceptionsHandler] ER_DUP_FIELDNAME: Duplicate column name 'EstateIntegrationEntity_estate_id' +1590ms
QueryFailedError: ER_DUP_FIELDNAME: Duplicate column name 'EstateIntegrationEntity_estate_id'
    at ...

We created a OneToOne relation from the EstateIntegrationEntity to the EstateEntity.

import { EstateEntity } from "src/estates/estate.entity";
import { Column, Entity, JoinColumn, OneToOne, PrimaryGeneratedColumn, RelationId } from "typeorm";

@Entity({ name: 'estate_integrations' })
export class EstateIntegrationEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @RelationId((estateIntegrationEntity: EstateIntegrationEntity) => estateIntegrationEntity.estate)
  estate_id: number;

  @OneToOne(() => EstateEntity, { eager: true })
  @JoinColumn({ name: 'estate_id' })
  estate: EstateEntity;

  ...
}

And a relation from the EstateEntity to the EstateIntegrationEntity :

import { EstateIntegrationEntity } from 'src/integrations/estate.integration.entity';
import { Column, Entity, JoinColumn, ManyToOne, OneToOne, PrimaryGeneratedColumn } from 'typeorm';

@Entity('estates')
export class EstateEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('varchar' || null)
  uuid: string;

  @OneToOne(
    () => EstateIntegrationEntity,
    estate_integration => estate_integration.estate,
  )
  estate_integration: EstateIntegrationEntity;
}

This error only occurs with .findOne() and not with .find():

async findEstateById(id: string): Promise<EstateIntegrationEntity> {
  return await this.estateIntegrationRepository.findOne({
    where: {
      external_id: id
    }
  });
}

Upvotes: 4

Views: 5509

Answers (2)

Ahmed E. Eldeeb
Ahmed E. Eldeeb

Reputation: 395

For this case you have 3 solution for this:

1- change column name from 'estate_id' to anything else like 'id_estate'

2- write custom join statement with TypeORM

3- my favorite solution is to use name strategy like this:

  • first install npm i --save typeorm-naming-strategies then in your typeorm config file
const SnakeNamingStrategy = require('typeorm-naming-strategies')
  .SnakeNamingStrategy;
   module.exports = {
        name: 'name',
        type: 'mysql',
        host: 'localhost',
        port: 3306,
       ...
       namingStrategy: new SnakeNamingStrategy(),
    }

Upvotes: 1

AyadRocketfy
AyadRocketfy

Reputation: 116

You can change the name of the fields. I just had a similar error and fixed it changing the name with @Column({ name: 'name_the_fields_with_different_name' }). Because the problem that if in the tables it has the same name when it does the find it has to fields with the same name.

Upvotes: 1

Related Questions