Repository navigation
Description
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
sgarner commentedon Sep 3, 2025
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
VetSpecialtyentity; then everything works correctly.ManyToManyis 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, defineManyToOneandOneToManyrelations from the two tables into and out of the intermediate entity.For example, if you wanted to start tracking the date that a
Vetgains particularSpecialty, this is the approach you'd want to use. You can't really do it withManyToMany.Here's what that looks like:
danielfrankcom/typeorm-repro@7d25c27
danielfrankcom commentedon Sep 3, 2025
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
OneToManyrelationships!sgarner commentedon Sep 3, 2025
The
JoinTabledecorator allows you to define the name of the table; it's set tovet_specialtyin your repro, but can be anything to match your DB schema.In fact the only thing tying the
VetSpecialtyentity to theVetorSpecialtyentities 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 theEntitydecorator onVetSpecialtyit would not change the name of theManyToManyjoin table (although it would fix the metadata conflict!).ragrag commentedon Sep 16, 2025
i will look into this more deeply 🙏🏻
itvby commentedon Sep 17, 2025
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:
An error occurs when attempting to delete a record of a related entity
FeedResourceEntity:ragrag commentedon Sep 17, 2025
@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
itvby commentedon Sep 17, 2025
@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.
itvby commentedon Sep 17, 2025
@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 --buildImportant: 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:
Delete Resource Error
Request:
Error Response:
{ "statusCode": 400, "message": "null value in column \"resource_id\" of relation \"feed_resources_categories\" violates not-null constraint" }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.
sgarner commentedon Sep 17, 2025
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
@ManyToManyat 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.
itvby commentedon Sep 17, 2025
@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 entityFeedTemplateCategoryEntity. At the same time, we would like to keep the ability to loadFeedResourceEntityrecords together with their relatedFeedCategoryEntityrecords directly, without going through the intermediate entity. To achieve this, we added the following field:We mark this field with
synchronize: falseso that it is ignored during migration generation. This allows us to fetchresourcestogether with theircategories.If the
@ManyToManydefinition is removed, we would need to rely on the intermediate relation (templatesCategories) instead.For example, with the current setup we can fetch
resourceswith theircategories(without loading intermediateresourcesCategories):Whereas without
@ManyToManywe would need: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 :)
sgarner commentedon Sep 17, 2025
I understand why you may want to do this. But the fact is the
ManyToManyfeature 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:
You would need to adjust how you fetch relations though.
michaelbromley commentedon Sep 19, 2025
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.
ragrag commentedon Sep 19, 2025
of course, I could try to find some capacity for it
ashwintemkar commentedon Sep 28, 2025
Hi @ragrag is this issue up for grabs, then I would like to look into it
ragrag commentedon Sep 29, 2025
@ashwintemkar sure, feel free to
ashwintemkar commentedon Sep 29, 2025
will raise a PR soon
ragrag commentedon Sep 29, 2025
you're referring to the original issue addressed by #11114 correct?
ashwintemkar commentedon Sep 29, 2025
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
ManyToManyrelationships 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
fix: prefer user defined junction metadata over auto generated to pre…
ashwintemkar commentedon Oct 10, 2025
I have raised a draft pull request, please review and let me know if more is needed from my side @ragrag @michaelbromley
AndKiel commentedon Nov 3, 2025
The same issue happens with OneToOne + JoinColumn.