Skip to content

Commit

Permalink
fix(core): initialize empty collections when fetch joining
Browse files Browse the repository at this point in the history
  • Loading branch information
B4nan committed Apr 24, 2021
1 parent 20ffb6f commit 02714e5
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion packages/knex/src/AbstractSqlDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,15 @@ export abstract class AbstractSqlDriver<C extends AbstractSqlConnection = Abstra
// If the primary key value for the relation is null, we know we haven't joined to anything
// and therefore we don't return any record (since all values would be null)
const hasPK = meta2.primaryKeys.every(pk => meta2.properties[pk].fieldNames.every(name => {
return Utils.isDefined(root![`${relationAlias}__${name}`], true);
return root![`${relationAlias}__${name}`] != null;
}));

if (!hasPK) {
// initialize empty collections
if ([ReferenceType.MANY_TO_MANY, ReferenceType.ONE_TO_MANY].includes(relation.reference)) {
result[relation.name] = result[relation.name] || [];
}

return;
}

Expand Down
16 changes: 16 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,22 @@ describe('QueryBuilder', () => {
await qb.execute();
});

test('join and select with empty collections', async () => {
const qb = orm.em.createQueryBuilder(FooBar2, 'fb');
qb.select('*')
.leftJoinAndSelect('fb.tests', 't')
.orderBy({ name: 1 });

await orm.em.nativeInsert(Test2, { id: 1, name: 't' });
await orm.em.nativeInsert(FooBar2, { id: 1, name: 'fb 1', tests: [] });
await orm.em.nativeInsert(FooBar2, { id: 2, name: 'fb 2', tests: [1] });
const res = await qb.getResultList();
expect(res[0].tests.isInitialized()).toBe(true);
expect(res[0].tests.getItems()).toHaveLength(0);
expect(res[1].tests.isInitialized()).toBe(true);
expect(res[1].tests.getItems()).toHaveLength(1);
});

test('select leftJoin 1:1 inverse', async () => {
const qb = orm.em.createQueryBuilder(FooBaz2, 'fz');
qb.select(['fb.*', 'fz.*'])
Expand Down

0 comments on commit 02714e5

Please sign in to comment.