Skip to content

@JoinColumn doesn't work more than once with same column #9814

@cverhoeven

Description

@cverhoeven

I just encountered some weird behaviour when trying to use @JoinColumn multiple times for the same column.
I've created a simple example to show the behaviour and make it reproducable:

@Entity()
export class TypeormTestPrimary {
  @PrimaryGeneratedColumn({
    type: 'int',
  })
  ID: number;

  @Column({
    type: 'int',
  })
  SecondaryID: number;

  @ManyToOne(() => TypeormTestSecondary)
  @JoinColumn({ name: 'SecondaryID', referencedColumnName: 'ID' })
  secondary: TypeormTestSecondary;

  @ManyToOne(() => TypeormTestTertiary)
  @JoinColumn({ name: 'SecondaryID', referencedColumnName: 'UserID' })
  tertiary: TypeormTestTertiary;
}

@Entity()
export class TypeormTestSecondary {
  @PrimaryGeneratedColumn({
    type: 'int',
  })
  ID: number;
}

@Entity()
export class TypeormTestTertiary {
  @PrimaryColumn({
    type: 'int',
  })
  SecondaryID: number;

  @PrimaryColumn({
    type: 'int',
  })
  UserID: number;
}

When trying to load the first entity TypeormTestPrimary with the secondary and tertiary relations, I'm getting the following error: Unknown column 'TypeormTestPrimary__TypeormTestPrimary_secondary.UserID' in 'on clause'.

The error shows that TypeORM tries to read the column UserID (which was used as the referenced column for the tertiary relation) on the TypeormTestSecondary entity, where the column obviously doesn't exist.
If I reverse the order of the relations it tries to do the same the other way around: It tries to read the column ID on the TypeormTestTertiary entity.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions