fix: update hasOne/belongsTo association values without foreign key (#5754)

This commit is contained in:
ChengLei Shao 2024-11-29 22:18:24 +08:00 committed by GitHub
parent 397e2165a8
commit bff82856e7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 43 additions and 1 deletions

View File

@ -26,6 +26,46 @@ describe('update associations', () => {
await db.close(); 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 () => { test('update belongs to with foreign key and object', async () => {
const throughAB = db.collection({ const throughAB = db.collection({
name: 'throughAB', name: 'throughAB',

View File

@ -350,7 +350,9 @@ export async function updateSingleAssociation(
} }
if (updateAssociationValues.includes(key)) { 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, { await updateAssociations(instance, value, {