fix: eager load belongs to many with through table (#1946)

* fix: eager load belongs to many with through table

* fix: test

* fix: instance accessor
This commit is contained in:
ChengLei Shao 2023-05-27 23:23:09 +08:00 committed by GitHub
parent 7d1a087b50
commit 29e66f675e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 2 deletions

View File

@ -56,6 +56,12 @@ describe('Eager loading tree', () => {
}); });
expect(a.get('bs')).toHaveLength(2); expect(a.get('bs')).toHaveLength(2);
const data = a.toJSON();
// @ts-ignore
const as = A.model.associations.bs.oneFromTarget.as;
expect(data['bs'][0][as]).toBeDefined();
}); });
it('should handle fields filter', async () => { it('should handle fields filter', async () => {

View File

@ -214,6 +214,7 @@ describe('associated field order', () => {
}); });
const p1JSON = p1Result.toJSON(); const p1JSON = p1Result.toJSON();
const p1Images = p1JSON['images']; const p1Images = p1JSON['images'];
expect(p1Images.map((i) => i['url'])).toEqual(['t2', 't1']); expect(p1Images.map((i) => i['url'])).toEqual(['t2', 't1']);
}); });

View File

@ -158,7 +158,7 @@ export class EagerLoadingTree {
const foreignKeyValues = node.parent.instances.map((instance) => instance.get(association.sourceKey)); const foreignKeyValues = node.parent.instances.map((instance) => instance.get(association.sourceKey));
const pivotAssoc = new HasOne(association.target, association.through.model, { const pivotAssoc = new HasOne(association.target, association.through.model, {
as: '_pivot', as: '_pivot_',
foreignKey: association.otherKey, foreignKey: association.otherKey,
sourceKey: association.targetKey, sourceKey: association.targetKey,
}); });
@ -252,9 +252,16 @@ export class EagerLoadingTree {
const sourceKey = association.sourceKey; const sourceKey = association.sourceKey;
const foreignKey = association.foreignKey; const foreignKey = association.foreignKey;
const as = association.oneFromTarget.as;
for (const instance of node.instances) { for (const instance of node.instances) {
// set instance accessor
instance[as] = instance.dataValues[as] = instance['_pivot_'];
delete instance.dataValues['_pivot_'];
delete instance['_pivot_'];
const parentInstance = node.parent.instances.find( const parentInstance = node.parent.instances.find(
(parentInstance) => parentInstance.get(sourceKey) == instance['_pivot'].get(foreignKey), (parentInstance) => parentInstance.get(sourceKey) == instance.dataValues[as].get(foreignKey),
); );
if (parentInstance) { if (parentInstance) {