fix: duplicated items in update associations (#4393)

* fix: data template middleware in data source

* fix: typo

* fix: duplicated items in update associations
This commit is contained in:
ChengLei Shao 2024-05-18 23:08:44 +08:00 committed by GitHub
parent 299c5a14cb
commit 144338be90
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 1 deletions

View File

@ -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<any>({ name: 'user01' });
await User.model.create<any>({ name: 'user02' });

View File

@ -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);
}