Skip to content

fix: prevent eager-loaded entities from overwriting manual relations - #11267

Merged
alumni merged 12 commits into
typeorm:masterfrom
LeviHeber:relations-eager-override-bug
Dec 5, 2025
Merged

alumni merged 12 commits into
typeorm:masterfrom
LeviHeber:relations-eager-override-bug

Conversation

@LeviHeber

@LeviHeber LeviHeber commented Jan 28, 2025 •

Copy link
Copy Markdown
Contributor

Description of change

The issue was caused by the way TypeORM processing queries. For each join, it checks if the join for that table exists. However, if the join has a condition, it will always add the join, even if a previous join for the same table already exists.

In the case of eager loading, TypeORM creates its own join, and since it has a DeleteDateColumn, an additional condition is added to the join (checking for a null DeletedDate). This newly added join does not match the manually specified join, and if the manual relation had additional nested fields that were not part of the eager load, those fields would be overwritten.

This fix addresses the issue by merging the manually requested relations with the eager-loaded data, preserving the complete details of the manual relations.

In issue #10426 , the same case was described, where there are 2 joins to the same table,
which causes performance issues.

The current fix does not change the join process and leaves both joins as they were,
but only fixes the consequences that were created as a result of it in the object creation,
because this is a consequence that is relevant both to this case and to other cases.

Unrelated, it should check how to deal with the problem of having 2 joins, for performance reasons.

Fixes: #11265
Fixes: #10812
Fixes: #9774
Fixes: #9581

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • npm run format to apply prettier formatting
  • npm run test passes with this change
  • This pull request links relevant issues as Fixes #0000
  • There are new or updated unit tests validating the change
  • N/A - Documentation has been updated to reflect this change
  • The new commits follow conventions explained in CONTRIBUTING.md

…ting manual relations

The issue was caused by the way TypeORM processing queries. For each join, it checks if the join for
that table exists. However, if the join has a condition, it will always add the join,
even if a previous join for the same table already exists.

In the case of eager loading, TypeORM creates its own join, and since it has a DeleteDateColumn,
an additional condition is added to the join (checking for a null DeletedDate).
This newly added join does not match the manually specified join,
and if the manual relation had additional nested fields that were not part of the eager load, those
fields would be overwritten.

This fix addresses the issue by merging the manually requested relations with the eager-loaded data,
preserving the complete details of the manual relations.

Closes: typeorm#11265
@coveralls

coveralls commented Jan 30, 2025 •

Copy link
Copy Markdown

Coverage Status

coverage: 80.773% (+0.002%) from 80.771%
when pulling 4e2bcf2 on LeviHeber:relations-eager-override-bug
into 6e34756 on typeorm:master.

@naorpeled naorpeled self-assigned this Feb 27, 2025
@coderabbitai

coderabbitai Bot commented Sep 18, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This PR fixes a bug in eager-relation handling by modifying the merge strategy in RelationMetadata to preserve manually requested nested relations. Instead of direct assignment, non-embedded entity values are now merged using OrmUtils.mergeDeep, preventing eager-loaded relations from overwriting nested relation data. Test cases updated to verify the fix.

Changes

Cohort / File(s) Summary
Core Logic Update
src/metadata/RelationMetadata.ts
Added OrmUtils import and modified setEntityValue to use merge strategy (OrmUtils.mergeDeep) for non-embedded paths instead of direct assignment, preserving nested relation data.
Entity Schema Updates
test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts, test/functional/relations/eager-relations/basic-eager-relations/entity/Profile.ts
Added deletedAt property with @DeleteDateColumn() and nestedProfile relation with @manytoone(() => Profile) to User entity; reordered imports in Profile.ts.
Test Case Updates
test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts
Added deletedAt: null to expected eager-loaded relation outputs; added new test "should preserve manually requested nested relations with DeleteDateColumn" validating nested relation preservation.

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant RelMeta as RelationMetadata<br/>(setEntityValue)
    participant Entity as Target Entity
    participant OrmUtils as OrmUtils

    rect rgb(220, 240, 255)
    note over RelMeta,Entity: Old Flow (Direct Assignment)
    App->>RelMeta: setEntityValue(entity, value)
    RelMeta->>Entity: entity[prop] = value
    note over Entity: ❌ Overwrites nested data
    end

    rect rgb(240, 255, 240)
    note over RelMeta,Entity: New Flow (Merge Strategy)
    App->>RelMeta: setEntityValue(entity, value)
    alt entity[prop] is object
        RelMeta->>OrmUtils: mergeDeep(entity[prop], value)
        OrmUtils->>Entity: Merged result
        note over Entity: ✓ Preserves nested relations
    else entity[prop] is primitive
        RelMeta->>Entity: entity[prop] = value
        note over Entity: Direct assignment
    end
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

The changes are focused and follow a consistent pattern (merge vs. assign logic), with straightforward test additions. However, understanding the implications of the merge strategy for relation handling requires some domain context.

Possibly related issues

Suggested labels

comp: relations, need review help, size-m

Suggested reviewers

  • sgarner
  • alumni

Poem

🐰 Nested relations, once were lost,
Eager loads would pay the cost,
Now we merge, don't just replace,
Nested data finds its place! ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "fix: prevent eager-loaded entities with DeleteDateColumn from overwriting manual relations" accurately and specifically describes the primary change in the changeset. The main fix modifies RelationMetadata.ts to use OrmUtils.mergeDeep instead of direct assignment in setEntityValue, which directly addresses the stated problem of eager-loaded relations with DeleteDateColumn overwriting manually specified nested relations. The title is concise, clear, and specific enough that a teammate scanning commit history would understand the core issue being resolved. The title is further validated by the test changes, which explicitly test the scenario of preserving manually requested nested relations with DeleteDateColumn.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Sep 18, 2025 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm/typeorm@11267
    

commit: 4e2bcf2

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/metadata/RelationMetadata.ts (1)

483-488: Docblock drift: remove stale “merge” parameter reference.

The comment mentions a merge flag that doesn’t exist. Update to reflect unconditional (scoped) merge behavior.

-     *
-     * If merge is set to true, it merges given value into currently
+     * Merges existing relation object fields from the entity when applicable (to‑one relations),
+     * then assigns the final value to the property.
test/github-issues/11265/issue-11265.ts (1)

48-56: Nit: fix comment to reflect entity name.

Rename “Retrieve user…” to “Retrieve parent…” for clarity.

-                // Retrieve user with manually specified nested relation
+                // Retrieve parent with manually specified nested relation
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa3cd43 and b42d508.

📒 Files selected for processing (5)
  • src/metadata/RelationMetadata.ts (1 hunks)
  • test/github-issues/11265/entity/parent.ts (1 hunks)
  • test/github-issues/11265/entity/relationEntity.ts (1 hunks)
  • test/github-issues/11265/entity/relationNestedEntity.ts (1 hunks)
  • test/github-issues/11265/issue-11265.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
test/github-issues/11265/entity/relationNestedEntity.ts (3)
test/github-issues/11265/entity/parent.ts (1)
  • Entity (4-11)
test/github-issues/11265/entity/relationEntity.ts (1)
  • Entity (8-18)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/metadata/RelationMetadata.ts (1)
src/util/ObjectUtils.ts (1)
  • ObjectUtils (3-82)
test/github-issues/11265/issue-11265.ts (1)
test/utils/test-utils.ts (3)
  • createTestingConnections (388-482)
  • reloadTestingDatabases (500-505)
  • closeTestingConnections (487-495)
test/github-issues/11265/entity/relationEntity.ts (5)
test/github-issues/11265/entity/parent.ts (1)
  • Entity (4-11)
test/github-issues/11265/entity/relationNestedEntity.ts (1)
  • Entity (3-7)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/columns/DeleteDateColumn.ts (1)
  • DeleteDateColumn (9-18)
src/decorator/relations/ManyToOne.ts (1)
  • ManyToOne (33-77)
test/github-issues/11265/entity/parent.ts (4)
test/github-issues/11265/entity/relationEntity.ts (1)
  • Entity (8-18)
test/github-issues/11265/entity/relationNestedEntity.ts (1)
  • Entity (3-7)
src/decorator/columns/PrimaryGeneratedColumn.ts (1)
  • PrimaryGeneratedColumn (55-119)
src/decorator/relations/ManyToOne.ts (1)
  • ManyToOne (33-77)
🔇 Additional comments (4)
test/github-issues/11265/entity/relationNestedEntity.ts (1)

3-7: LGTM.

Minimal entity for nesting; appropriate for the scenario.

test/github-issues/11265/entity/parent.ts (1)

9-11: LGTM.

Eager relation on ParentEntity correctly models the issue.

test/github-issues/11265/entity/relationEntity.ts (1)

13-18: LGTM.

DeleteDateColumn + nested relation nicely reproduces the original bug.

src/metadata/RelationMetadata.ts (1)

523-526: Guard merge: restrict ObjectUtils.assign to to‑one, non‑lazy plain‑object relations

File: src/metadata/RelationMetadata.ts (lines 523-526)

Risk: merging when value is undefined/primitive, lazy (Promise) or to‑many (array) can throw or corrupt/duplicate relation data — only merge plain objects for to‑one, non‑lazy relations.

Apply:

-            if (ObjectUtils.isObject(entity[propertyName]))
-                ObjectUtils.assign(value, entity[propertyName])
-            entity[propertyName] = value
+            // Merge existing manual relation fields into the incoming value only for to‑one relations.
+            if (
+                !this.isOneToMany &&
+                !this.isManyToMany &&
+                !this.isLazy &&
+                ObjectUtils.isObject(value) &&
+                ObjectUtils.isObject(entity[propertyName])
+            ) {
+                ObjectUtils.assign(value, entity[propertyName])
+            }
+            entity[propertyName] = value

Tests to add:

  • many-to-many / one-to-many assignments — ensure no duplication or array-index/length corruption.
  • lazy relation property — ensure a Promise is not merged into the target object.

Comment thread test/github-issues/11265/issue-11265.ts Resolved
@gioboa
gioboa requested a review from alumni September 18, 2025 06:46

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @LeviHeber, thanks for this great PR, can you fix up the sap tests please?

Comment thread test/github-issues/11265/issue-11265.ts Resolved
@gioboa
gioboa requested a review from alumni September 18, 2025 12:48

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your help @LeviHeber

@LeviHeber

Copy link
Copy Markdown
Contributor Author

i left the test to be describe.only. is it need to be fixed?

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, remove the .only please

@LeviHeber

Copy link
Copy Markdown
Contributor Author

I removed the only and pushed it again.
It seems that more tests are running now, but for some reason many of the tests encounter the same check (commands - migration create: should write Javascript empty migration file when option is passed) and it doesn't seem to be related to the fix I made.
I would appreciate some guidance.

@sgarner

sgarner commented Sep 19, 2025

Copy link
Copy Markdown
Collaborator

I removed the only and pushed it again. It seems that more tests are running now, but for some reason many of the tests encounter the same check (commands - migration create: should write Javascript empty migration file when option is passed) and it doesn't seem to be related to the fix I made. I would appreciate some guidance.

That sounds possibly related to #11653 which has been fixed now. Tests are passing in this PR.

Comment thread test/github-issues/11265/issue-11265.ts Resolved
Comment thread src/metadata/RelationMetadata.ts Resolved
@LeviHeber

Copy link
Copy Markdown
Contributor Author

I made the following fixes:

  1. Moved the test to its proper place in the eager-relations feature tests.
  2. Updated the fix to work with OrmUtils.mergeDeep instead of ObjectUtils.assign

@LeviHeber
LeviHeber requested a review from sgarner September 21, 2025 09:48
@LeviHeber

Copy link
Copy Markdown
Contributor Author

Is there anything else that needs to be done to move forward?

@naorpeled

Copy link
Copy Markdown
Member

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 20, 2025

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts (1)

27-28: Consider making nestedProfile optional for type safety.

The nestedProfile field is declared as non-optional but won't be populated in all test scenarios (e.g., in the first test case at lines 65-131). While this works in practice since it's test code, making it optional would better reflect its usage.

Apply this diff to improve type accuracy:

-    @ManyToOne(() => Profile)
-    nestedProfile: Profile
+    @ManyToOne(() => Profile)
+    nestedProfile?: Profile
test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts (1)

150-187: Excellent test coverage for the bug fix!

The test case comprehensively validates that manually requested nested relations are preserved when DeleteDateColumn is present. The flow is clear: create nested relation, link it, retrieve with manual relations specification, and assert preservation.

One minor enhancement to consider: the test currently asserts that the manually requested nestedProfile is preserved, but it could also verify that the eager-loaded user.profile relation is still correctly loaded alongside it (e.g., retrievedEditor!.user.profile.about.should.equal("I cut trees!")). This would provide additional confidence that the merge doesn't break eager relations.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b42d508 and edfb29c.

📒 Files selected for processing (4)
  • src/metadata/RelationMetadata.ts (2 hunks)
  • test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts (3 hunks)
  • test/functional/relations/eager-relations/basic-eager-relations/entity/Profile.ts (1 hunks)
  • test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • test/functional/relations/eager-relations/basic-eager-relations/entity/Profile.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/metadata/RelationMetadata.ts
🔇 Additional comments (3)
test/functional/relations/eager-relations/basic-eager-relations/entity/User.ts (1)

7-7: LGTM!

The combined import statement is clean and follows TypeScript conventions.

test/functional/relations/eager-relations/basic-eager-relations/basic-eager-relations.ts (2)

107-107: LGTM!

Correctly adds the expected deletedAt: null value for the eagerly loaded author relation, reflecting the new DeleteDateColumn on the User entity.


121-121: LGTM!

Correctly adds the expected deletedAt: null value for the eagerly loaded editor.user relation, consistent with the DeleteDateColumn addition.

@gioboa gioboa left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

May I ask you to solve the conflicts please?
Thanks for your help @LeviHeber

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Dec 1, 2025 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 4e2bcf2

CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate value before merging

Before merging a relation's value, add a check to ensure the new value is also
an object. This prevents incorrect merge attempts when the new value is null or
undefined.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: This suggestion correctly identifies that if value is null or not an object, the current logic would incorrectly attempt to merge it instead of replacing the existing relation, which could lead to unexpected behavior. Adding a check for ObjectUtils.isObject(value) makes the new merging logic more robust.

Medium
  • More

Previous suggestions

Suggestions up to commit 0ef98b3
CategorySuggestion                                                                                                                                    Impact
Possible issue
Handle null values in relation merge

Modify the deep merge condition to also check if the new value is a non-null
object. This prevents incorrect merge attempts when clearing a relation by
setting it to null.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value) && value !== null) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 8

__

Why: The suggestion correctly identifies a bug in the new logic where attempting to set a relation to null would fail if the relation property already holds an object, instead trying to merge null. The proposed fix ensures relations can be correctly cleared.

Medium
Prevent merging array-based relations

Prevent deep-merging for array-based relations (one-to-many, many-to-many) by
adding a check to ensure neither the existing property nor the new value is an
array. Arrays should be replaced, not merged.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && !Array.isArray(entity[propertyName]) && !Array.isArray(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly points out that deep-merging arrays for to-many relations is generally undesirable and could lead to unexpected data states. Replacing the array is the standard behavior, and the proposed change correctly enforces this, preventing a potential bug.

Medium
Suggestions up to commit 3539087
CategorySuggestion                                                                                                                                    Impact
General
Limit merge to eager relations only

Restrict the deep merge logic to apply only to eager relations by adding a
condition this.isEager. This avoids changing the standard behavior of replacing
non-eager relation objects on assignment.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+// Only merge for eager-loaded relations to preserve manually requested nested relations
+const shouldMerge = this.isEager && ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value)
+if (shouldMerge) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 9

__

Why: This is an excellent suggestion that correctly infers the PR's intent is to fix an issue with eager relations. Limiting the merge logic to only eager relations by checking this.isEager prevents an unintended breaking change for non-eager relations, where replacement is the expected behavior.

High
Possible issue
Check value is object before merging

Before merging a relation's value, add a check to ensure the new value is also
an object. This prevents errors when clearing a relation by setting it to null
or undefined.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies a potential runtime error when trying to set a relation to null or undefined, as OrmUtils.mergeDeep would likely fail. Adding a check for ObjectUtils.isObject(value) is a crucial fix for the new logic.

Medium
Suggestions up to commit 28c9e7d
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate value type before merging

Add a check to ensure the new value is also an object before attempting to merge
it, otherwise perform a direct assignment.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 7

__

Why: The suggestion correctly identifies a potential issue where OrmUtils.mergeDeep could be called with a non-object value (e.g., null), preventing relations from being cleared and possibly causing runtime errors.

Medium
Suggestions up to commit ac46664
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate value type before merging

Modify the condition to merge properties only if both the existing property and
the new value are objects. Otherwise, perform a direct assignment.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 7

__

Why: This is a valid suggestion that improves the robustness of the new logic by ensuring OrmUtils.mergeDeep is only called when both the existing property and the new value are objects, preventing incorrect merges with null or primitive values.

Medium
Suggestions up to commit 877fda4
CategorySuggestion                                                                                                                                    Impact
Possible issue
Validate value type before merging

Before merging, check if the new value is also an object. If not, perform a
direct assignment to correctly handle cases like setting a relation to null.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && ObjectUtils.isObject(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 8

__

Why: This is a valid and important correction to the new logic. Without checking if value is an object, calling OrmUtils.mergeDeep with null or a primitive value would likely cause a runtime error or unexpected behavior when trying to clear a relation.

Medium
Handle array relations correctly

Avoid using mergeDeep for array-based relations (one-to-many, many-to-many).
Check if the property or value is an array and use direct assignment instead of
merging to prevent incorrect behavior.

src/metadata/RelationMetadata.ts [524-528]

-if (ObjectUtils.isObject(entity[propertyName])) {
+if (ObjectUtils.isObject(entity[propertyName]) && !Array.isArray(entity[propertyName]) && !Array.isArray(value)) {
     OrmUtils.mergeDeep(entity[propertyName], value)
 } else {
     entity[propertyName] = value
 }
Suggestion importance[1-10]: 8

__

Why: This suggestion correctly identifies that mergeDeep is not suitable for arrays, which are common in to-many relations. Applying a deep merge on arrays would lead to incorrect behavior, so checking for arrays and falling back to assignment is a crucial fix to prevent breaking to-many relations.

Medium

@gioboa
gioboa dismissed sgarner’s stale review December 2, 2025 19:50

All the requested changes are now implemented.

@alumni

alumni commented Dec 4, 2025

Copy link
Copy Markdown
Collaborator

I think the issue that we have could possibly be a bit earlier, when we build the query. It seems we select the user twice - maybe once because it's an eagerly loaded relation and another time because it was requested by the user.

In the test we have:

await connection.manager.findOne(
    Editor,
    {
        where: { userId: 1 },
        relations: {
            user: {
                nestedProfile: true,
            },
        },
    },
)

which generates the query:

SELECT
    "Editor"."userId" AS "Editor_userId",
    "Editor"."postId" AS "Editor_postId",
    "Editor__Editor_user"."id" AS "Editor__Editor_user_id",
    "Editor__Editor_user"."firstName" AS "Editor__Editor_user_firstName",
    "Editor__Editor_user"."lastName" AS "Editor__Editor_user_lastName",
    "Editor__Editor_user"."deletedAt" AS "Editor__Editor_user_deletedAt",
    "Editor__Editor_user"."profileId" AS "Editor__Editor_user_profileId",
    "Editor__Editor_user"."nestedProfileId" AS "Editor__Editor_user_nestedProfileId",
    "Editor__Editor_user__Editor__Editor_user_nestedProfile"."id" AS "Editor__Editor_user__Editor__Editor_user_nestedProfile_id",
    "Editor__Editor_user__Editor__Editor_user_nestedProfile"."about" AS "Editor__Editor_user__Editor__Editor_user_nestedProfile_about",
    "Editor__Editor_user__Editor__Editor_user_profile"."id" AS "Editor__Editor_user__Editor__Editor_user_profile_id",
    "Editor__Editor_user__Editor__Editor_user_profile"."about" AS "Editor__Editor_user__Editor__Editor_user_profile_about",
    "Editor__user"."id" AS "Editor__user_id",
    "Editor__user"."firstName" AS "Editor__user_firstName",
    "Editor__user"."lastName" AS "Editor__user_lastName",
    "Editor__user"."deletedAt" AS "Editor__user_deletedAt",
    "Editor__user"."profileId" AS "Editor__user_profileId",
    "Editor__user"."nestedProfileId" AS "Editor__user_nestedProfileId",
    "Editor__user__profile"."id" AS "Editor__user__profile_id",
    "Editor__user__profile"."about" AS "Editor__user__profile_about"
FROM
    "editor" "Editor"
    LEFT JOIN "user" "Editor__Editor_user" ON "Editor__Editor_user"."id" = "Editor"."userId"
    AND ("Editor__Editor_user"."deletedAt" IS NULL)
    LEFT JOIN "profile" "Editor__Editor_user__Editor__Editor_user_nestedProfile" ON "Editor__Editor_user__Editor__Editor_user_nestedProfile"."id" = "Editor__Editor_user"."nestedProfileId"
    LEFT JOIN "profile" "Editor__Editor_user__Editor__Editor_user_profile" ON "Editor__Editor_user__Editor__Editor_user_profile"."id" = "Editor__Editor_user"."profileId"
    LEFT JOIN "user" "Editor__user" ON "Editor__user"."id" = "Editor"."userId"
    AND ("Editor__user"."deletedAt" IS NULL)
    LEFT JOIN "profile" "Editor__user__profile" ON "Editor__user__profile"."id" = "Editor__user"."profileId"
WHERE
    ((("Editor"."userId" = 1)))
    AND (
        "Editor"."userId" = 1
        AND "Editor"."postId" = 1
    )

We have both Editor__Editor_user+Editor__Editor_user__Editor__Editor_user_profile and Editor__user+Editor__user__profile.

I'll check tomorrow to see if this is intended.

@alumni

alumni commented Dec 5, 2025 •

Copy link
Copy Markdown
Collaborator

We'll create a separate issue for the extra things in the join so we don't block this.

Later edit: created #11823.

@alumni alumni changed the title fix: prevent eager-loaded entities with DeleteDateColumn from overwriting manual relations fix: prevent eager-loaded entities from overwriting manual relations Dec 5, 2025
@alumni
alumni merged commit 2d8c515 into typeorm:master Dec 5, 2025
mgohin pushed a commit to mgohin/typeorm that referenced this pull request Jan 15, 2026
kranners pushed a commit to kranners/typeorm that referenced this pull request Mar 1, 2026
@michaelbromley michaelbromley mentioned this pull request Mar 13, 2026
18 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

6 participants