Skip to content

Commit

Permalink
fix(query-builder): respect qb.joinAndSelect when serializing
Browse files Browse the repository at this point in the history
Closes #4034
Closes #3812
  • Loading branch information
B4nan committed Feb 9, 2023
1 parent 4ad4cdf commit 4025869
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
26 changes: 25 additions & 1 deletion packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import type {
RequiredEntityData,
} from '@mikro-orm/core';
import {
helper,
LoadStrategy,
LockMode,
PopulateHint,
Expand Down Expand Up @@ -632,7 +633,30 @@ export class QueryBuilder<T extends object = AnyEntity> {
res = this.driver.mergeJoinedResult(res, this.mainAlias.metadata!);
}

return res.map(r => this.em!.map<T>(this.mainAlias.entityName, r, { schema: this._schema }));
const entities: T[] = [];

function propagatePopulateHint<U>(entity: U, hint: PopulateOptions<U>[]) {
helper(entity).__serializationContext.populate ??= hint;
hint.forEach(pop => {
const value = entity[pop.field];

if (Utils.isEntity<U>(value, true)) {
helper(value).populated();
propagatePopulateHint(value, pop.children ?? []);
} else if (Utils.isCollection(value)) {
value.populated();
value.getItems(false).forEach(item => propagatePopulateHint(item, pop.children ?? []));
}
});
}

for (const r of res) {
const entity = this.em!.map<T>(this.mainAlias.entityName, r, { schema: this._schema });
propagatePopulateHint(entity, this._populate);
entities.push(entity);
}

return entities;
}

/**
Expand Down
2 changes: 2 additions & 0 deletions tests/issues/GH3812.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ test('GH 3812', async () => {
const res1 = await orm.em.find(SerialNumber, {}, { populate: ['logs.step'] });
expect(res1).toHaveLength(1);
expect(wrap(res1[0]).toJSON().logs[0].serialNumber).toBe('559fccf7-11f0-4e5a-8e15-ae29b98ddeb3');
expect(wrap(res1[0]).toJSON().logs[0].step?.name).toBe('ASSY');

orm.em.clear();

Expand All @@ -185,4 +186,5 @@ test('GH 3812', async () => {
.getResultList();
expect(res2).toHaveLength(1);
expect(wrap(res2[0]).toJSON().logs[0].serialNumber).toBe('559fccf7-11f0-4e5a-8e15-ae29b98ddeb3');
expect(wrap(res2[0]).toJSON().logs[0].step?.name).toBe('ASSY');
});

0 comments on commit 4025869

Please sign in to comment.