From 144338be90ceacce71110868153de2cd919748d9 Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Sat, 18 May 2024 23:08:44 +0800 Subject: [PATCH] fix: duplicated items in update associations (#4393) * fix: data template middleware in data source * fix: typo * fix: duplicated items in update associations --- .../src/__tests__/update-associations.test.ts | 22 +++++++++++++++++++ .../core/database/src/update-associations.ts | 13 ++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/core/database/src/__tests__/update-associations.test.ts b/packages/core/database/src/__tests__/update-associations.test.ts index 16a26bab24..30854d8a8f 100644 --- a/packages/core/database/src/__tests__/update-associations.test.ts +++ b/packages/core/database/src/__tests__/update-associations.test.ts @@ -240,6 +240,28 @@ describe('update associations', () => { afterEach(async () => { await db.close(); }); + + it('should update association values', async () => { + const user1 = await User.repository.create({ + values: { + name: 'u1', + posts: [{ name: 'u1t1' }], + }, + }); + + // update with associations + const updateRes = await User.repository.update({ + filterByTk: user1.get('id'), + values: { + name: 'u1', + posts: [{ id: user1.get('posts')[0].get('id'), name: 'u1t1' }], + }, + updateAssociationValues: ['comments'], + }); + + expect(updateRes[0].toJSON()['posts'].length).toBe(1); + }); + it('user.posts', async () => { await User.model.create({ name: 'user01' }); await User.model.create({ name: 'user02' }); diff --git a/packages/core/database/src/update-associations.ts b/packages/core/database/src/update-associations.ts index 76cb90647d..14629cb1a3 100644 --- a/packages/core/database/src/update-associations.ts +++ b/packages/core/database/src/update-associations.ts @@ -538,9 +538,20 @@ export async function updateMultipleAssociation( associationContext: association, updateAssociationValues: keys, }); + newItems.push(instance); } } - model.setDataValue(key, setItems.concat(newItems)); + for (const newItem of newItems) { + const existIndexInSetItems = setItems.findIndex((setItem) => setItem[targetKey] === newItem[targetKey]); + + if (existIndexInSetItems !== -1) { + setItems[existIndexInSetItems] = newItem; + } else { + setItems.push(newItem); + } + } + + model.setDataValue(key, setItems); }