Skip to content

TypeORM generates invalid column name for relation when referencedColumnName is used with another composite relation #7242

Closed

Description

@falahati

Issue Description

TypeORM generates an invalid column name for relation when referencedColumnName is used with another composite relation.
This seems like some sort of caching. Apparently, we missed the possibility of one field getting used in two or more relations.

Consider the following entities:

game.entity.ts

@Entity()
export class Game extends BaseEntity {
    @PrimaryGeneratedColumn({ name: "id" })
    public id!: number;
}

participant.entity.ts

@Entity()
export class Participant extends BaseEntity {
    @PrimaryColumn({ name: "user_id", type: "int", nullable: false })
    @Index()
    public userId!: number;

    @PrimaryColumn({ name: "game_id", type: "int", nullable: false })
    @Index()
    public gameId!: number;
}

match.entity.ts

@Entity()
export class Match extends BaseEntity {
    @PrimaryGeneratedColumn({ name: "id" })
    public id!: number;

    @JoinColumn({ name: "game_id", referencedColumnName: "id" })
    @ManyToOne(() => Game, (e) => e.id, { eager: true })
    public game!: Game;

    @Column({ name: "user_id", type: "int", nullable: false })
    public userId!: number;

    @JoinColumn(
        [
            { name: "game_id", referencedColumnName: "gameId" },
            { name: "user_id", referencedColumnName: "userId" },
        ]
    )
    @ManyToOne(() => Participant, { eager: true })
    public participant: Participant | null = null;
}

And the following piece of code:

const query = this.matches.createQueryBuilder("match");
query.leftJoinAndSelect("match.game", "game");
console.log(query.getSql());

Expected Behavior

Should not confuse two different relations with each other and generate the following query:

SELECT
   "match"."id" AS "match_id",
   "match"."user_id" AS "match_user_id",
   "match"."game_id" AS "match_game_id",
   "game"."id" AS "game_id" 
FROM
   "match" "match" 
   LEFT JOIN
      "game" "game" 
      ON "game"."id" = "match"."game_id"

Actual Behavior

SELECT
   "match"."id" AS "match_id",
   "match"."user_id" AS "match_user_id",
   "match"."game_id" AS "match_game_id",
   "game"."id" AS "game_id" 
FROM
   "match" "match" 
   LEFT JOIN
      "game" "game" 
      ON game.gameId = "match"."game_id"

The problem is with the game.gameId = "match"."game_id". As you can clearly see, TypeORM thinks that it should use gameId for the name of the field in a relationship that has nothing to do with gameId. This value is probably selected based on the referencedColumnName of the other composite relation on the entity.

Steps to Reproduce

Discussed above

My Environment

  "dependencies": {
    "@nestjs/core": "^7.6.1",
    "pg": "^8.5.1",
    "reflect-metadata": "^0.1.13",
    "typeorm": "^0.2.29"
  },

Relevant Database Driver(s)

  • aurora-data-api
  • aurora-data-api-pg
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

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

  • Yes, I have the time, and I know how to start.
  • Yes, I have the time, but I don't know how to start. I would need guidance.
  • No, I don't have the time, although I believe I could do it if I had the time...
  • No, I don't have the time and I wouldn't even know how to start.

Activity

  1. falahati commented on Jan 3, 2021

    @falahati
    Author

    Workaround:

    @Entity()
    export class Game extends BaseEntity {
        @PrimaryGeneratedColumn({ name: "id" })
        public gameId!: number;
    }
  2. piotr-pawlowski commented on Jul 1, 2021

    @piotr-pawlowski

    I have the same problem. Did you find a workround?

  3. falahati commented on Jul 1, 2021

    @falahati
    Author

    the second comment is the workaround. rename the id property to the value provided for the referencedColumnName for now until this is fixed.
    in other words, all referencedColumnNames for a name should have the same value pointing to properties with the same name.

  4. imnotjames commented on Jul 1, 2021

    @imnotjames
    Contributor

    Pretty sure this would be resolved by #7805

  5. piotr-pawlowski commented on Jul 1, 2021

    @piotr-pawlowski

    Pretty sure this would be resolved by #7805

    When will it be accepted and merged?

  6. oskarbero commented on Jan 17, 2023

    @oskarbero

    Pretty sure this would be resolved by #7805

    Bumping this reply as I ran into the same issue, any news on this PR being merged?

  7. daitay4 commented on Jan 23, 2023

    @daitay4

    Pretty sure this would be resolved by #7805

    Seems like this PR was already merged quite some time ago, yet this issue still persists using the latest (0.3.11) version.

    Anyone has any solution that does not include changing the property name as in suggested workaround?

    Any hope for it being fixed soon? Maybe due to another PR?

    I'm using mysql btw.

  8. bwermes commented on Apr 7, 2023

    @bwermes

    I can confirm this issue is still present on 0.3.13 and MySQL.

    In my case:

    TimeCard entity

        @ManyToOne(() => UserJob, (userJob) => userJob.timeCards, { onDelete: "CASCADE" })
        @JoinColumn([
            { name: "userId", referencedColumnName: "userId" },
            { name: "jobId", referencedColumnName: "jobId" },
            { name: "venueId", referencedColumnName: "venueId" },
        ])
        userJob: UserJob;
    
        @ManyToOne(() => Venue, (venue) => venue.timeCards, { onDelete: "CASCADE" })
        @JoinColumn({ name: "venueId" })
        venue: Venue;

    UserJob entity

        @PrimaryColumn({ type: "varchar", length: 36 })
        userId: string;
    
        @PrimaryColumn({ type: "varchar", length: 36 })
        jobId: string;
    
        @PrimaryColumn({ type: "varchar", length: 36 })
        venueId: string;
    
        @OneToMany(() => TimeCard, (timeCards) => timeCards.userJob)
        timeCards: TimeCard[];

    Performing a findOne on entity TimeCard with relation to userJob results in:

    {
        "error": "Unknown column 'Job.jobId' in 'on clause'; Error code: 1054; SQLState: 42S22"
    }

    Resulting SQL:

    SELECT `UserJob`.`createdAt` AS `UserJob_createdAt`,
     `UserJob`.`updatedAt` AS `UserJob_updatedAt`,
     `UserJob`.`recordVersion` AS `UserJob_recordVersion`,
     `UserJob`.`deletedAt` AS `UserJob_deletedAt`,
     `UserJob`.`userId` AS `UserJob_userId`,
     `UserJob`.`jobId` AS `UserJob_jobId`,
     `UserJob`.`venueId` AS `UserJob_venueId`,
     `UserJob`.`enforceWorkSchedule` AS `UserJob_enforceWorkSchedule`,
     `UserJob__payRates`.`createdAt` AS `UserJob__payRates_createdAt`,
     `UserJob__payRates`.`updatedAt` AS `UserJob__payRates_updatedAt`,
     `UserJob__payRates`.`recordVersion` AS `UserJob__payRates_recordVersion`,
     `UserJob__payRates`.`deletedAt` AS `UserJob__payRates_deletedAt`,
     `UserJob__payRates`.`id` AS `UserJob__payRates_id`,
     `UserJob__payRates`.`userId` AS `UserJob__payRates_userId`,
     `UserJob__payRates`.`venueId` AS `UserJob__payRates_venueId`,
     `UserJob__payRates`.`jobId` AS `UserJob__payRates_jobId`,
     `UserJob__payRates`.`effectiveAt` AS `UserJob__payRates_effectiveAt`,
     `UserJob__payRates`.`endedAt` AS `UserJob__payRates_endedAt`,
     `UserJob__payRates`.`isActive` AS `UserJob__payRates_isActive`,
     `UserJob__payRates`.`basePayRateTotal` AS `UserJob__payRates_basePayRateTotal` FROM `UserJob` `UserJob` 
    LEFT JOIN `UserPayRate` `UserJob__payRates` ON `UserJob__payRates`.`userId`=`UserJob`.`userId`
    AND `UserJob__payRates`.`venueId`=`UserJob`.`venueId`
    AND `UserJob__payRates`.`jobId`=`UserJob`.`jobId`
    AND (`UserJob__payRates`.`deletedAt` IS NULL)  INNER JOIN `TimeCard` `TimeCard` ON  `TimeCard`.`userId` = `UserJob`.`userId`
    AND `TimeCard`.`jobId` = `UserJob`.`jobId`
    AND `TimeCard`.`deletedAt` IS NULL WHERE ( `TimeCard`.`id` IN (:param_0) )
    AND ( `UserJob`.`deletedAt` IS NULL )

    As noted by others above, I believe Typeorm is trying to reuse the JoinColumn properties for venueId which relates to Venue.id

  9. hainguyen8y commented on Jun 27, 2023

    @hainguyen8y

    #7207 (comment)
    This comment helps me!

  10. MatthijsReyers commented on Mar 4, 2024

    @MatthijsReyers

    Still running in to this issue in 2024 as of version 0.3.20. Our solution is to find the relation entity on its own and then search on the join column instead of the whole entity.

    This is really annoying though as it means we're doing a completely unnecessary extra query...

    Edit: we're using MySQL

  11. BrandonNoad commented on Jan 14, 2025

    @BrandonNoad

    We are experiencing this issue as well. Using a MySQL data source and [email protected].

    If you have a find with multiple nested relations and the relations are based on multi-column FKs, then TypeORM doesn't generate the correct SQL (the LEFT JOIN ON column names are incorrect).

    Here is an example that does not work as expected:

    const result = await repository.findOne({
       where: { id },
       relations: {
          messages: {
             user: true,
             attachments: {
                file: {
                   type: true,
                },
             },
          },
       },
    });
    
  12. christhekeele commented on Aug 12, 2025

    @christhekeele

    Still running into this issue in 2025. Added a composite relation to one of my god objects and 50% of my queries broke from this spooky action at a distance. Took me the whole day to find that this was the issue, and another half of a day to apply the workaround everywhere. Postgres, [email protected].

    Keywords missing from this issue that would have helped me find it much sooner are "unquoted" and "lowercased". As in, the erroneous reference typeorm generates when this issue happens is a suprising unquoted entityName.relatedId, which unquoted in PG is treated at entityname.relatedid, vs an expected "entityName"."relatedId". Reporting here in hopes of helping this surface to the confused googler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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