Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(sql): add support for sub-queries #525

Merged
merged 1 commit into from
Apr 29, 2020
Merged

feat(sql): add support for sub-queries #525

merged 1 commit into from
Apr 29, 2020

Commits on Apr 29, 2020

  1. feat(sql): add support for sub-queries

    You can use sub-queries in selects or in where conditions. To select subquery, use `qb.as(alias)` method:
    
    ```typescript
    const knex = orm.em.getKnex();
    const qb1 = orm.em.createQueryBuilder(Book2, 'b').count('b.uuid', true).where({ author: knex.ref('a.id') }).as('Author2.booksTotal');
    const qb2 = orm.em.createQueryBuilder(Author2, 'a');
    qb2.select(['*', qb1]).orderBy({ booksTotal: 'desc' });
    
    console.log(qb2.getQuery());
    // select `a`.*, (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) as `books_total` from `author2` as `a` order by `books_total` desc
    ```
    
    When you want to filter by sub-query, you will need to register it first via `qb.withSubquery()`:
    
    > The dynamic property (`booksTotal`) needs to be defined at the entity level (as `persist: false`).
    > You always need to use prefix in the `qb.withSchema()` (so `a.booksTotal`).
    
    ```typescript
    const knex = orm.em.getKnex();
    const qb1 = orm.em.createQueryBuilder(Book2, 'b').count('b.uuid', true).where({ author: knex.ref('a.id') }).getKnexQuery();
    const qb2 = orm.em.createQueryBuilder(Author2, 'a');
    qb2.select('*').withSubQuery(qb1, 'a.booksTotal').where({ 'a.booksTotal': { $in: [1, 2, 3] } });
    
    console.log(qb2.getQuery());
    // select `a`.* from `author2` as `a` where (select count(distinct `b`.`uuid_pk`) as `count` from `book2` as `b` where `b`.`author_id` = `a`.`id`) in (?, ?, ?)
    ```
    B4nan committed Apr 29, 2020
    Configuration menu
    Copy the full SHA
    9bf54ce View commit details
    Browse the repository at this point in the history