Skip to content

Commit

Permalink
fix(query-builder): don't remove joins used by other joins during pag…
Browse files Browse the repository at this point in the history
…ination (#5566)

Fixes  #5565

---------

Co-authored-by: Martin Adámek <banan23@gmail.com>
  • Loading branch information
AdriVanHoudt and B4nan committed May 14, 2024
1 parent 67c5e43 commit b05c434
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
17 changes: 16 additions & 1 deletion packages/knex/src/query/QueryBuilder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1596,8 +1596,23 @@ export class QueryBuilder<T extends object = AnyEntity> {
}

addPath(this._populate);
const joins = Object.entries(this._joins);
const rootAlias = this.alias;

for (const [key, join] of Object.entries(this._joins)) {
function addParentAlias(alias: string) {
const join = joins.find(j => j[1].alias === alias);

if (join && join[1].ownerAlias !== rootAlias) {
orderByAliases.push(join[1].ownerAlias);
addParentAlias(join[1].ownerAlias);
}
}

for (const orderByAlias of orderByAliases) {
addParentAlias(orderByAlias);
}

for (const [key, join] of joins) {
const path = join.path?.replace(/\[populate]|\[pivot]|:ref/g, '').replace(new RegExp(`^${meta.className}.`), '');

if (!populate.has(path ?? '') && !orderByAliases.includes(join.alias)) {
Expand Down
12 changes: 12 additions & 0 deletions tests/QueryBuilder.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -705,6 +705,18 @@ describe('QueryBuilder', () => {
expect(qb.getParams()).toEqual(['foo', 1]);
});

test('GH #5565', async () => {
const qb = orm.em.createQueryBuilder(Author2, 'a');
qb.select('*')
.limit(1)
.orderBy({ books: { tags: { id: QueryOrder.ASC } } })
.populate([{ field: 'friends' }]);

await qb;
expect(qb.getQuery()).toEqual('select `a`.* from `author2` as `a` left join `book2` as `e1` on `a`.`id` = `e1`.`author_id` left join `book2_tags` as `e2` on `e1`.`uuid_pk` = `e2`.`book2_uuid_pk` where `a`.`id` in (select `a`.`id` from (select `a`.`id` from `author2` as `a` left join `book2` as `e1` on `a`.`id` = `e1`.`author_id` left join `book2_tags` as `e2` on `e1`.`uuid_pk` = `e2`.`book2_uuid_pk` group by `a`.`id` order by min(`e2`.`book_tag2_id`) asc limit ?) as `a`) order by `e2`.`book_tag2_id` asc');
expect(qb.getParams()).toEqual([1]);
});

test('select by 1:m', async () => {
const qb = orm.em.createQueryBuilder(Author2);
qb.select('*').where({ books: { $in: ['123', '321'] } });
Expand Down

0 comments on commit b05c434

Please sign in to comment.