Skip to content

Commit

Permalink
feat(knex): allow changing FROM clause using QueryBuilder
Browse files Browse the repository at this point in the history
closes #3374
  • Loading branch information
derevnjuk committed Aug 9, 2022
1 parent 73a0ab3 commit 50e5fdc
Show file tree
Hide file tree
Showing 5 changed files with 217 additions and 84 deletions.
28 changes: 28 additions & 0 deletions docs/docs/query-builder.md
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,34 @@ const count = await qb.getCount();

This will also remove any existing limit and offset from the query (the QB will be cloned under the hood, so calling `getCount()` does not mutate the original QB state).

## Overriding FROM clause

You can specify the table used in the `FROM` clause, replacing the current table name if one has already been specified. This is typically used to specify a sub-query expression in SQL.

```ts
const qb = em.createQueryBuilder(Book2);
qb.select('*').from(Author2).where({ id: { $gt: 2 } });
// select `e0`.* from `author2` as `e0` where `e0`.`id` > 2;
```

You can also use sub-queries in the `FROM` like this:

```ts
const qb1 = em.createQueryBuilder(Book2).where({ id: { $lte: new Date() } }).orderBy({ id: 'DESC' }).limit(10);
const qb2 = em.createQueryBuilder(Book2).from(qb.clone())
qb.select('*').orderBy({ id: 'ASC' });
// select `e1`.* from (select `e0`.* from `book2` as `e0` where `e0`.`id` <= ? order by `e0`.`id` desc limit ?) as `e1` order by `e1`.`id`;
```

To set up an alias to refer to a table in a `SELECT` statement, pass the second argument as follows:

```ts
const qb1 = em.createQueryBuilder(Book2, 'b1').where({ id: { $lte: new Date() } }).orderBy({ id: 'DESC' }).limit(10);
const qb2 = em.createQueryBuilder(Book2, 'b2').from(qb.clone())
qb.select('*').orderBy({ id: 'ASC' });
// select `b2`.* from (select `b1`.* from `book2` as `b1` where `b1`.`id` <= ? order by `b1`.`id` desc limit ?) as `b2` order by `b2`.`id`;
```

## Using sub-queries

You can filter using sub-queries in where conditions:
Expand Down
15 changes: 15 additions & 0 deletions packages/knex/src/query/Alias.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { Knex } from 'knex';
import type { EntityMetadata } from '@mikro-orm/core';

export class Alias {

aliasName!: string;
entityName!: string;
metadata?: EntityMetadata;
subQuery?: Knex.QueryBuilder;

constructor(params: Alias) {
Object.assign(this, params);
}

}
Loading

0 comments on commit 50e5fdc

Please sign in to comment.