fix: through collection records should not be reset (#1377)

* fix: through collection records should not be reset

* fix: test error
This commit is contained in:
chenos 2023-01-17 09:44:53 +08:00 committed by GitHub
parent 2d767be184
commit 47158e0282
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 76 additions and 3 deletions

View File

@ -0,0 +1,66 @@
import { Database } from '../database';
import { mockDatabase } from './';
describe('update through', () => {
let db: Database;
beforeEach(async () => {
db = mockDatabase();
await db.clean({ drop: true });
});
afterEach(async () => {
await db.close();
});
it('should not be reset', async () => {
db.collection({
name: 'c',
autoGenId: true,
fields: [
{
name: 'id',
type: 'integer',
primaryKey: true,
autoIncrement: true,
}
],
});
db.collection({
name: 'a',
fields: [
{
type: 'string',
name: 'name',
},
{
type: 'belongsToMany',
name: 'b',
target: 'b',
through: 'c',
},
],
});
db.collection({
name: 'b',
fields: [],
});
await db.sync();
const b = await db.getRepository('b').create({
values: {},
});
const a = await db.getRepository('a').create({
values: {
b: [b.toJSON()],
},
});
const c1 = await db.getRepository('c').findOne();
await db.getRepository('a').update({
filterByTk: a.id,
values: {
b: [b.toJSON()],
},
});
const c2 = await db.getRepository('c').findOne();
expect(c1.get('id')).toBe(c2.get('id'))
});
});

View File

@ -6,7 +6,7 @@ import {
HasOne,
Hookable,
ModelStatic,
Transactionable,
Transactionable
} from 'sequelize';
import { Model } from './model';
import { UpdateGuard } from './update-guard';
@ -402,6 +402,7 @@ export async function updateMultipleAssociation(
const list1 = []; // to be setted
const list2 = []; // to be added
const created = [];
for (const item of value) {
if (isUndefinedOrNull(item)) {
continue;
@ -413,6 +414,11 @@ export async function updateMultipleAssociation(
} else if (item.sequelize) {
list1.push(item);
} else if (typeof item === 'object') {
const targetKey = (association as any).targetKey || 'id';
if (item[targetKey]) {
created.push(item[targetKey]);
list1.push(item[targetKey]);
}
list2.push(item);
}
}
@ -456,8 +462,9 @@ export async function updateMultipleAssociation(
continue;
}
const addAccessor = association.accessors.add;
await model[addAccessor](item[pk], accessorOptions);
if (!created.includes(item[pk])) {
await model[addAccessor](item[pk], accessorOptions);
}
if (!recursive) {
continue;
}