diff --git a/packages/core/database/src/__tests__/eager-loading/eager-loading-tree.test.ts b/packages/core/database/src/__tests__/eager-loading/eager-loading-tree.test.ts index c51fb935e..822e74d7f 100644 --- a/packages/core/database/src/__tests__/eager-loading/eager-loading-tree.test.ts +++ b/packages/core/database/src/__tests__/eager-loading/eager-loading-tree.test.ts @@ -56,6 +56,12 @@ describe('Eager loading tree', () => { }); 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 () => { diff --git a/packages/core/database/src/__tests__/field-options/sort-by.test.ts b/packages/core/database/src/__tests__/field-options/sort-by.test.ts index 27afa1121..e9f194606 100644 --- a/packages/core/database/src/__tests__/field-options/sort-by.test.ts +++ b/packages/core/database/src/__tests__/field-options/sort-by.test.ts @@ -214,6 +214,7 @@ describe('associated field order', () => { }); const p1JSON = p1Result.toJSON(); + const p1Images = p1JSON['images']; expect(p1Images.map((i) => i['url'])).toEqual(['t2', 't1']); }); diff --git a/packages/core/database/src/eager-loading/eager-loading-tree.ts b/packages/core/database/src/eager-loading/eager-loading-tree.ts index 49cdb2005..da60ec53d 100644 --- a/packages/core/database/src/eager-loading/eager-loading-tree.ts +++ b/packages/core/database/src/eager-loading/eager-loading-tree.ts @@ -158,7 +158,7 @@ export class EagerLoadingTree { const foreignKeyValues = node.parent.instances.map((instance) => instance.get(association.sourceKey)); const pivotAssoc = new HasOne(association.target, association.through.model, { - as: '_pivot', + as: '_pivot_', foreignKey: association.otherKey, sourceKey: association.targetKey, }); @@ -252,9 +252,16 @@ export class EagerLoadingTree { const sourceKey = association.sourceKey; const foreignKey = association.foreignKey; + const as = association.oneFromTarget.as; + 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( - (parentInstance) => parentInstance.get(sourceKey) == instance['_pivot'].get(foreignKey), + (parentInstance) => parentInstance.get(sourceKey) == instance.dataValues[as].get(foreignKey), ); if (parentInstance) {