fix: slow find with include in mysql (#1304)

* fix: slow find with include in mysql

* fix: test

* fix: test

* chore: console.log

* chore: test
This commit is contained in:
ChengLei Shao 2022-12-31 22:35:12 +08:00 committed by GitHub
parent a98c9e03ce
commit 33377c7d3a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 3 deletions

View File

@ -249,7 +249,7 @@ describe('has many repository', () => {
expect(p1.title).toEqual('u1t1'); expect(p1.title).toEqual('u1t1');
}); });
test('find', async () => { test('find with has many', async () => {
const u1 = await User.repository.create({ values: { name: 'u1' } }); const u1 = await User.repository.create({ values: { name: 'u1' } });
const t1 = await Tag.repository.create({ values: { name: 't1' } }); const t1 = await Tag.repository.create({ values: { name: 't1' } });

View File

@ -269,7 +269,12 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
attributes: [primaryKeyField], attributes: [primaryKeyField],
group: `${model.name}.${primaryKeyField}`, group: `${model.name}.${primaryKeyField}`,
transaction, transaction,
}) include: opts.include.filter((include) => {
return (
Object.keys(include.where || {}).length > 0 || JSON.stringify(opts?.filter)?.includes(include.association)
);
}),
} as any)
).map((row) => { ).map((row) => {
return { row, pk: row.get(primaryKeyField) }; return { row, pk: row.get(primaryKeyField) };
}); });
@ -278,6 +283,16 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
return []; return [];
} }
const templateModel = await model.findOne({
...opts,
includeIgnoreAttributes: false,
attributes: [primaryKeyField],
group: `${model.name}.${primaryKeyField}`,
transaction,
limit: 1,
offset: 0,
} as any);
const where = { const where = {
[primaryKeyField]: { [primaryKeyField]: {
[Op.in]: ids.map((id) => id['pk']), [Op.in]: ids.map((id) => id['pk']),
@ -297,7 +312,7 @@ export class Repository<TModelAttributes extends {} = any, TCreationAttributes e
return { rows, include }; return { rows, include };
}); });
}), }),
templateModel: ids[0].row, templateModel: templateModel,
}); });
} else { } else {
rows = await model.findAll({ rows = await model.findAll({