Skip to content

Many-to-many relationships broken when user-defined junction entity exists (0.3.26 regression) #11637

Open

Description

@danielfrankcom

Issue description

TypeORM 0.3.26 appears to have changed behavior for many-to-many relationships when user-defined junction entities exist. The relationship data is not being persisted correctly, with junction table rows containing NULL values instead of the expected foreign key relationships.

Expected Behavior

In TypeORM <=0.3.25, junction table should be populated with proper foreign key values:

INSERT INTO "vet_specialty"("vet_id", "specialty_name") VALUES ($1, $2), ($3, $4) -- PARAMETERS: [1,"dogs",1,"cats"]

Junction table contains relationship data, queries return related entities.

> npm install [email protected] --no-save && npm test

changed 1 package, and audited 140 packages in 1s

found 0 vulnerabilities

> [email protected] test
> ts-node test.ts

query: SELECT version()
query: SELECT * FROM current_schema()
query: SELECT "Specialty"."name" AS "Specialty_name" FROM "specialty" "Specialty" WHERE "Specialty"."name" IN ($1, $2) -- PARAMETERS: ["dogs","cats"]
query: START TRANSACTION
query: INSERT INTO "specialty"("name") VALUES ($1), ($2) -- PARAMETERS: ["dogs","cats"]
query: COMMIT
query: SELECT "Specialty"."name" AS "Specialty_name" FROM "specialty" "Specialty" WHERE "Specialty"."name" IN ($1, $2) -- PARAMETERS: ["dogs","cats"]
query: START TRANSACTION
query: INSERT INTO "vet"("name") VALUES ($1) RETURNING "id" -- PARAMETERS: ["Carlos Salazar"]
query: INSERT INTO "vet_specialty"("vet_id", "specialty_name") VALUES ($1, $2), ($3, $4) -- PARAMETERS: [1,"dogs",1,"cats"]
query: COMMIT
query: SELECT DISTINCT "distinctAlias"."Vet_id" AS "ids_Vet_id" FROM (SELECT "Vet"."id" AS "Vet_id", "Vet"."name" AS "Vet_name", "Vet__Vet_specialties"."name" AS "Vet__Vet_specialties_name" FROM "vet" "Vet" LEFT JOIN "vet_specialty" "Vet_Vet__Vet_specialties" ON "Vet_Vet__Vet_specialties"."vet_id"="Vet"."id" LEFT JOIN "specialty" "Vet__Vet_specialties" ON "Vet__Vet_specialties"."name"="Vet_Vet__Vet_specialties"."specialty_name" WHERE (("Vet"."id" = $1))) "distinctAlias" ORDER BY "Vet_id" ASC LIMIT 1 -- PARAMETERS: [1]
query: SELECT "Vet"."id" AS "Vet_id", "Vet"."name" AS "Vet_name", "Vet__Vet_specialties"."name" AS "Vet__Vet_specialties_name" FROM "vet" "Vet" LEFT JOIN "vet_specialty" "Vet_Vet__Vet_specialties" ON "Vet_Vet__Vet_specialties"."vet_id"="Vet"."id" LEFT JOIN "specialty" "Vet__Vet_specialties" ON "Vet__Vet_specialties"."name"="Vet_Vet__Vet_specialties"."specialty_name" WHERE ( (("Vet"."id" = $1)) ) AND ( "Vet"."id" IN (1) ) -- PARAMETERS: [1]
Vet specialties count: 2
Expected: 2, Actual: 2

> psql -d postgres -c "SELECT * FROM vet_specialty"
 id | vet_id | specialty_name
----+--------+----------------
  1 |      1 | dogs
  2 |      1 | cats
(2 rows)

Actual Behavior

In TypeORM >=0.3.26, junction table gets rows with NULL/DEFAULT values:

INSERT INTO "vet_specialty"("vet_id", "specialty_name") VALUES (DEFAULT, DEFAULT), (DEFAULT, DEFAULT) RETURNING "id"

Junction table contains empty rows, queries return no related entities.

> npm install [email protected] --no-save && npm test

changed 1 package, and audited 140 packages in 933ms

found 0 vulnerabilities

> [email protected] test
> ts-node test.ts

query: SELECT version()
query: SELECT * FROM current_schema()
query: SELECT "Specialty"."name" AS "Specialty_name" FROM "specialty" "Specialty" WHERE "Specialty"."name" IN ($1, $2) -- PARAMETERS: ["dogs","cats"]
query: START TRANSACTION
query: INSERT INTO "specialty"("name") VALUES ($1), ($2) -- PARAMETERS: ["dogs","cats"]
query: COMMIT
query: SELECT "Specialty"."name" AS "Specialty_name" FROM "specialty" "Specialty" WHERE "Specialty"."name" IN ($1, $2) -- PARAMETERS: ["dogs","cats"]
query: START TRANSACTION
query: INSERT INTO "vet"("name") VALUES ($1) RETURNING "id" -- PARAMETERS: ["Carlos Salazar"]
query: INSERT INTO "vet_specialty"("vet_id", "specialty_name") VALUES (DEFAULT, DEFAULT), (DEFAULT, DEFAULT) RETURNING "id"
query: COMMIT
query: SELECT DISTINCT "distinctAlias"."Vet_id" AS "ids_Vet_id" FROM (SELECT "Vet"."id" AS "Vet_id", "Vet"."name" AS "Vet_name", "Vet__Vet_specialties"."name" AS "Vet__Vet_specialties_name" FROM "vet" "Vet" LEFT JOIN "vet_specialty" "Vet_Vet__Vet_specialties" ON "Vet_Vet__Vet_specialties"."vet_id"="Vet"."id" LEFT JOIN "specialty" "Vet__Vet_specialties" ON "Vet__Vet_specialties"."name"="Vet_Vet__Vet_specialties"."specialty_name" WHERE (("Vet"."id" = $1))) "distinctAlias" ORDER BY "Vet_id" ASC LIMIT 1 -- PARAMETERS: [1]
query: SELECT "Vet"."id" AS "Vet_id", "Vet"."name" AS "Vet_name", "Vet__Vet_specialties"."name" AS "Vet__Vet_specialties_name" FROM "vet" "Vet" LEFT JOIN "vet_specialty" "Vet_Vet__Vet_specialties" ON "Vet_Vet__Vet_specialties"."vet_id"="Vet"."id" LEFT JOIN "specialty" "Vet__Vet_specialties" ON "Vet__Vet_specialties"."name"="Vet_Vet__Vet_specialties"."specialty_name" WHERE ( (("Vet"."id" = $1)) ) AND ( "Vet"."id" IN (1) ) -- PARAMETERS: [1]
Vet specialties count: 0
Expected: 2, Actual: 0

> psql -d postgres -c "SELECT * FROM vet_specialty"
 id | vet_id | specialty_name
----+--------+----------------
  1 |        |
  2 |        |
(2 rows)

Steps to reproduce

Minimal reproducer available at danielfrankcom/typeorm-repro.

The reproducer includes a simple many-to-many relationship with a user-defined junction entity. Running the test with TypeORM 0.3.25 vs 0.3.26 shows the different behavior.

If the vet_specialty table is created in migration.sql but the VetSpecialty entity is not defined in entities.ts, the junction table works and produces the expected result. The existence of the junction table entity seems to cause the difference in behavior.

My Environment

Dependency Version
Operating System MacOS
Node.js version v22.18.0
Typescript version 5.9.2
TypeORM version 0.3.26

Additional Context

This behavior change appears to be related to PR #11114, which addressed duplicate metadata issues for user-defined junction tables. The change may have affected how junction metadata is created when explicit junction entities are present.

Relevant Database Driver(s)

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

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

No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

Activity

  1. sgarner commented on Sep 3, 2025

    @sgarner
    Collaborator

    This does look like a bug. @ragrag Are you able to investigate the cause of this issue introduced in #11114?

    As a workaround, I would suggest not to define the join table as an entity. In your reproduction example, that simply means removing the superfluous definition of the VetSpecialty entity; then everything works correctly.

    ManyToMany is a shortcut which automatically creates the join table to link two relations and access them as arrays from each end of the join. In this case you shouldn't (and don't need to) use the join table as an entity itself.

    In case you want to add additional fields to the join table, then you should define the intermediate entity yourself and stop using ManyToMany. Instead, define ManyToOne and OneToMany relations from the two tables into and out of the intermediate entity.

    For example, if you wanted to start tracking the date that a Vet gains particular Specialty, this is the approach you'd want to use. You can't really do it with ManyToMany.

    Here's what that looks like:
    danielfrankcom/typeorm-repro@7d25c27

  2. added
    regression
    and removed on Sep 3, 2025
  3. danielfrankcom commented on Sep 3, 2025

    @danielfrankcom
    Author

    Thanks, it did seem like there was a better way to define the relationship than what is in the reproducer, but figured I'd write up the report anyway since it was working previously.

    I can confirm that without the entity definition the relationship works properly. Worth noting though that in my sample the junction table is created with a custom migration script, so the table name isn't necessarily predictable without the entity definition, and is at the whim of TypeORM internals.

    Appreciate the detail in the example you provided with the OneToMany relationships!

  4. sgarner commented on Sep 3, 2025

    @sgarner
    Collaborator

    Worth noting though that in my sample the junction table is created with a custom migration script, so the table name isn't necessarily predictable without the entity definition, and is at the whim of TypeORM internals.

    The JoinTable decorator allows you to define the name of the table; it's set to vet_specialty in your repro, but can be anything to match your DB schema.

    In fact the only thing tying the VetSpecialty entity to the Vet or Specialty entities and their automatic join table is the fact that it has been given the same name in the database. If you changed the name in the Entity decorator on VetSpecialty it would not change the name of the ManyToMany join table (although it would fix the metadata conflict!).

  5. ragrag commented on Sep 16, 2025

    @ragrag
    Contributor

    i will look into this more deeply 🙏🏻

  6. itvby commented on Sep 17, 2025

    @itvby

    Similar problem :( With the new version, I started getting the error, example: "Property "resource_id" was not found in "FeedResourceCategoryEntity". Make sure your query is correct.
    When trying to delete an entity, the field exists in the specified entity:

    @Entity({ name: `${FEED_PREFIX_TABLE_NAME}resources_categories` })
    @Index(['resourceId', 'categoryId'], { unique: true })
    export class FeedResourceCategoryEntity extends BaseEntity {
      @Column('uuid')
      resourceId!: string;
    
      @Column('uuid')
      categoryId!: string;
    
      @Column({ nullable: true })
      order!: number | null;
    
      // RELATIONSHIPS
    
      @ManyToOne(() => FeedResourceEntity, (resource) => resource.resourcesCategories, {
        onDelete: 'CASCADE',
      })
      resource?: FeedResourceEntity;
    
      @ManyToOne(() => FeedCategoryEntity, (category) => category.resourcesCategories, {
        onDelete: 'CASCADE',
      })
      category?: FeedCategoryEntity;
    }
    @Entity({ name: `${FEED_PREFIX_TABLE_NAME}resources` })
    export class FeedResourceEntity extends BaseEntity {
      @Column()
      title!: string;
    
      @Column()
      alias!: string;
    
      @Column()
      slug!: string;
    
      @Column({ type: 'enum', enum: FeedResourceType })
      type!: FeedResourceType;
    
      @Column()
      url!: string;
    
      @Column({ nullable: true })
      internalTitle!: string | null;
    
      @Column({ nullable: true })
      internalDescription!: string | null;
    
      // RELATIONSHIPS
    
      @OneToMany(() => FeedResourceCategoryEntity, (resourceCategory) => resourceCategory.resource)
      resourcesCategories?: FeedResourceCategoryEntity[];
    
      @ManyToMany(() => FeedCategoryEntity, (category) => category.resources)
      @JoinTable({
        name: `${FEED_PREFIX_TABLE_NAME}resources_categories`,
        joinColumn: {
          name: 'resource_id',
          referencedColumnName: 'id',
        },
        inverseJoinColumn: {
          name: 'category_id',
          referencedColumnName: 'id',
        },
        synchronize: false,
      })
      categories?: FeedCategoryEntity[];
    }

    An error occurs when attempting to delete a record of a related entity FeedResourceEntity :

      @ApiBearerAuth(EMPLOYEE_ACCESS_TOKEN_STRATEGY_NAME)
      @UseGuards(EmployeeAccessTokenGuard)
      @Delete(':resourceId')
      deleteOneFeedResourceById(@Param('resourceId') resourceId: string) {
        return this.feedResourceService.deleteOneBy({ id: resourceId });
      }
  7. ragrag commented on Sep 17, 2025

    @ragrag
    Contributor

    @itvby can you provide a runnable reproduction 🙏🏻 ?

    i cannot tell if its truly a regression from #11114 or not but here you are directly deleting from a table not a junction table

  8. itvby commented on Sep 17, 2025

    @itvby

    @ragrag I just checked it code in version 0.3.25, and everything works as before. I'll isolate the issue to a separate repository soon and let you know. Thanks.

  9. itvby commented on Sep 17, 2025

    @itvby

    @ragrag This project demonstrates a TypeORM (v0.3.26) bug that occurs when creating and deleting entities with many-to-many relationships.

    Important: These errors occur only in TypeORM version 0.3.26. In version 0.3.25, all operations work correctly without any constraint violations.

    Start services:

    # Development
    cp env.example .env
    docker-compose -f docker-compose.dev.yml up --build

    Important: Migrations and seeds are launched automatically.

    Create Resource Error

    Request:

    POST http://localhost:3000/feeds/resources
    Content-Type: application/json
    
    {
        "title": "React Documentation",
        "type": "documentation",
        "url": "https://react.dev",
        "categoryIds": ["550e8400-e29b-41d4-a716-446655440003"]
    }

    Error Response:

    {
        "statusCode": 400,
        "message": "null value in column \"resource_id\" of relation \"feed_resources_categories\" violates not-null constraint"
    }

    SQL Statement:

    INSERT INTO "feed_resources_categories"("id", "created_at", "updated_at", "resource_id", "category_id", "order") VALUES (DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT, DEFAULT) RETURNING "id", "created_at", "updated_at"

    Delete Resource Error

    Request:

    DELETE http://localhost:3000/feeds/resources/6ba7b810-9dad-11d1-80b4-00c04fd430c8

    Error Response:

    {
        "statusCode": 400,
        "message": "null value in column \"resource_id\" of relation \"feed_resources_categories\" violates not-null constraint"
    }
    Image

    Summary

    This indicates a problem with TypeORM's handling of many-to-many relationships where the foreign key constraints are not being properly managed during entity operations.

    Important: These errors occur only in TypeORM version 0.3.26. In version 0.3.25, all operations work correctly without any constraint violations.

    Image Image Image
  10. sgarner commented on Sep 17, 2025

    @sgarner
    Collaborator

    Looking at this reproduction I would argue that this is again an entity design issue: it is a mistake to define the junction entity yourself and use @ManyToMany at the same time.

    However, this also implies that #11114 was not fully considered. Given the unexpectedly breaking nature of that change, I'm starting to think it should be reverted.

  11. itvby commented on Sep 17, 2025

    @itvby

    @sgarner thank you for your reply.

    We intentionally chose the current entity definitions because the join table requires a custom field (order). For this reason, we explicitly defined the intermediate entity FeedTemplateCategoryEntity. At the same time, we would like to keep the ability to load FeedResourceEntity records together with their related FeedCategoryEntity records directly, without going through the intermediate entity. To achieve this, we added the following field:

      @ManyToMany(() => FeedCategoryEntity, (category) => category.templates)
      @JoinTable({
        name: 'feed_templates_categories',
        joinColumn: {
          name: 'template_id',
          referencedColumnName: 'id',
        },
        inverseJoinColumn: {
          name: 'category_id',
          referencedColumnName: 'id',
        },
        synchronize: false,
      })
      categories?: FeedCategoryEntity[];
    

    We mark this field with synchronize: false so that it is ignored during migration generation. This allows us to fetch resources together with their categories.
    If the @ManyToMany definition is removed, we would need to rely on the intermediate relation (templatesCategories) instead.

    For example, with the current setup we can fetch resources with their categories (without loading intermediate resourcesCategories):

      async findAll(): Promise<FeedResourceEntity[]> {
        return this.feedResourceRepository.find({
          relations: { categories: true },
        });
      }
    

    Whereas without @ManyToMany we would need:

      async findAll(): Promise<FeedResourceEntity[]> {
        return this.feedResourceRepository.find({
          relations: { resourcesCategories: { category: true } },
        });
      }
    

    Since much of the existing codebase already works with the former approach, this pattern has been practical for us so far.

    We hope this clarifies the reasoning behind our implementation :)

  12. sgarner commented on Sep 17, 2025

    @sgarner
    Collaborator

    I understand why you may want to do this. But the fact is the ManyToMany feature wasn't designed with this in mind, and so the approach is problematic. Even if we revert #11114 to resolve this issue, it will bring back other issues which that PR was trying to fix.

    For the same convenience with a custom junction table, you might consider creating a getter method instead:

    get categories(): FeedCategoryEntity[] | undefined {
      return this.resourcesCategories?.map(resourceCategory => resourceCategory.category);
    }

    You would need to adjust how you fetch relations though.

  13. michaelbromley commented on Sep 19, 2025

    @michaelbromley
    Member

    We should revert (PR above) and then for the subsequent release, see if we can re-implement the fix without the regression. @ragrag if you have any ideas & capacity to explore that, it would be great.

  14. ragrag commented on Sep 19, 2025

    @ragrag
    Contributor

    We should revert (PR above) and then for the subsequent release, see if we can re-implement the fix without the regression. @ragrag if you have any ideas & capacity to explore that, it would be great.

    of course, I could try to find some capacity for it

  15. ashwintemkar commented on Sep 28, 2025

    @ashwintemkar

    Hi @ragrag is this issue up for grabs, then I would like to look into it

  16. ragrag commented on Sep 29, 2025

    @ragrag
    Contributor

    @ashwintemkar sure, feel free to

  17. ashwintemkar commented on Sep 29, 2025

    @ashwintemkar

    @ashwintemkar sure, feel free to

    will raise a PR soon

  18. ragrag commented on Sep 29, 2025

    @ragrag
    Contributor

    @ashwintemkar sure, feel free to

    will raise a PR soon

    you're referring to the original issue addressed by #11114 correct?

  19. ashwintemkar commented on Sep 29, 2025

    @ashwintemkar

    @ashwintemkar sure, feel free to

    will raise a PR soon

    you're referring to the original issue addressed by #11114 correct?

    Yes, correct, I’m referring to the original issue addressed by #11114
    and I am trying to find a potential solution that preserves the original fix (avoiding metadata conflicts) without breaking support for ManyToMany relationships involving explicitly defined junction entities.

    I'll share a draft PR soon for early feedback. Appreciate all the groundwork you’ve already done on this, thank you

  20. ashwintemkar commented on Oct 10, 2025

    @ashwintemkar

    I have raised a draft pull request, please review and let me know if more is needed from my side @ragrag @michaelbromley

  21. AndKiel commented on Nov 3, 2025

    @AndKiel

    The same issue happens with OneToOne + JoinColumn.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugregression

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions