From bff82856e7af4e8d6d09ae7b2bc432a6ab71efc3 Mon Sep 17 00:00:00 2001 From: ChengLei Shao Date: Fri, 29 Nov 2024 22:18:24 +0800 Subject: [PATCH] fix: update hasOne/belongsTo association values without foreign key (#5754) --- .../src/__tests__/update-associations.test.ts | 40 +++++++++++++++++++ .../core/database/src/update-associations.ts | 4 +- 2 files changed, 43 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 30854d8a8f..e20e8ef602 100644 --- a/packages/core/database/src/__tests__/update-associations.test.ts +++ b/packages/core/database/src/__tests__/update-associations.test.ts @@ -26,6 +26,46 @@ describe('update associations', () => { await db.close(); }); + it('should update has one association with foreign key', async () => { + const User = db.collection({ + name: 'users', + fields: [ + { type: 'string', name: 'name' }, + { type: 'hasOne', name: 'profile', foreignKey: 'userId', target: 'profiles' }, + ], + }); + + const Profile = db.collection({ + name: 'profiles', + fields: [ + { type: 'string', name: 'name' }, + { type: 'bigInt', name: 'userId' }, + { type: 'belongsTo', name: 'user', foreignKey: 'userId' }, + ], + }); + + await db.sync(); + + // create user + const user = await User.repository.create({ values: { name: 'user1' } }); + const profile = await Profile.repository.create({ values: { name: 'profile1' } }); + + const profileData = profile.toJSON(); + await User.repository.update({ + filterByTk: user.id, + values: { + profile: { + ...profileData, + userId: null, + }, + }, + updateAssociationValues: ['profile'], + }); + + const profile1 = await Profile.repository.findOne({ filterByTk: profile.id }); + expect(profile1['userId']).toBe(user.id); + }); + test('update belongs to with foreign key and object', async () => { const throughAB = db.collection({ name: 'throughAB', diff --git a/packages/core/database/src/update-associations.ts b/packages/core/database/src/update-associations.ts index d7889fc60c..ce973e5328 100644 --- a/packages/core/database/src/update-associations.ts +++ b/packages/core/database/src/update-associations.ts @@ -350,7 +350,9 @@ export async function updateSingleAssociation( } if (updateAssociationValues.includes(key)) { - await instance.update(value, { ...options, transaction }); + const updateValues = { ...value }; + delete updateValues[association.foreignKey]; + await instance.update(updateValues, { ...options, transaction }); } await updateAssociations(instance, value, {