Skip to content

Commit

Permalink
fix: upsertWithReplace should delete non-persist relationship fields … (
Browse files Browse the repository at this point in the history
#6960)

…before upsert
  • Loading branch information
sradevski authored Apr 5, 2024
1 parent 9ccd88d commit a0005fa
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,38 @@ describe("mikroOrmRepository", () => {
)
})

it("should clear the parent entity from the one-to-many relation", async () => {
const entity1 = {
id: "1",
title: "en1",
entity2: [{ title: "en2-1", entity1: null }],
}

await manager1().upsertWithReplace([entity1], {
relations: ["entity2"],
})
const listedEntities = await manager1().find({
where: { id: "1" },
options: { populate: ["entity2"] },
})

expect(listedEntities).toHaveLength(1)
expect(listedEntities[0]).toEqual(
expect.objectContaining({
id: "1",
title: "en1",
})
)
expect(listedEntities[0].entity2.getItems()).toHaveLength(1)
expect(listedEntities[0].entity2.getItems()).toEqual(
expect.arrayContaining([
expect.objectContaining({
title: "en2-1",
}),
])
)
})

it("should only update the parent entity of a one-to-many if relation is not included", async () => {
const entity1 = {
id: "1",
Expand Down
10 changes: 10 additions & 0 deletions packages/utils/src/dal/mikro-orm/mikro-orm-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,16 @@ export function mikroOrmBaseRepositoryFactory<T extends object = object>(
Object.assign(normalizedDataItem, {
...joinColumnsConstraints,
})
// Non-persist relation columns should be removed before we do the upsert.
Object.entries(relation.targetMeta?.properties ?? {})
.filter(
([_, propDef]) =>
propDef.persist === false &&
propDef.reference === ReferenceType.MANY_TO_ONE
)
.forEach(([key]) => {
delete normalizedDataItem[key]
})
})

await this.upsertMany_(manager, relation.type, normalizedData)
Expand Down

0 comments on commit a0005fa

Please sign in to comment.