Skip to content

Commit

Permalink
feat(querybuilder): Added groupBy clause
Browse files Browse the repository at this point in the history
  • Loading branch information
Rawphs committed Oct 27, 2016
1 parent b36adf3 commit 3fad91a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/EntityRepository.ts
Expand Up @@ -82,6 +82,10 @@ export class EntityRepository<T> {
queryBuilder.offset(options.offset);
}

if (options.groupBy) {
queryBuilder.groupBy(options.groupBy);
}

if (options.join && Array.isArray(options.join)) {
options.join.forEach(join => {
let column = join as string;
Expand Down Expand Up @@ -132,6 +136,7 @@ export class EntityRepository<T> {

export interface FindOptions {
orderBy?: any,
groupBy?: any,
alias?: string,
limit?: number,
offset?: number,
Expand Down
57 changes: 57 additions & 0 deletions src/QueryBuilder.ts
Expand Up @@ -41,6 +41,11 @@ export class QueryBuilder<T> {
*/
private appliedPrimaryKeys: {[key: string]: string} = {};

/**
* @type {Array}
*/
private groupBys: Array<{groupBy: string | Array<string>}> = [];

/**
* @type {Array}
*/
Expand Down Expand Up @@ -325,6 +330,7 @@ export class QueryBuilder<T> {
this.criteria.applyStaged();
this.applySelects();
this.applyOrderBys();
this.applyGroupBys();

this.prepared = true;

Expand Down Expand Up @@ -497,6 +503,57 @@ export class QueryBuilder<T> {
return this;
}

/**
* Set the group by.
*
* .groupBy('name')
* .groupBy(['name'])
* .groupBy(['name', 'age'])
*
* @param {string|string[]} groupBy
*
* @returns {QueryBuilder}
*/
public groupBy(groupBy: string | Array<string>): this {
this.groupBys.push({groupBy});

return this;
}

/**
* Apply group by to the query.
*
* @param {string|string[]} groupBy
*
* @returns {QueryBuilder}
*/
private applyGroupBy(groupBy: string | Array<string>): this {
let properties = [];

if (typeof groupBy === 'string') {
properties.push(this.criteria.mapToColumn(groupBy));
} else if (Array.isArray(groupBy)) {
groupBy.forEach(group => properties.push(this.criteria.mapToColumn(group)));
}

this.statement.groupBy(properties);

return this;
}

/**
* Apply group-by statements to the query.
*
* @returns {QueryBuilder}
*/
private applyGroupBys(): this {
this.groupBys.forEach(groupBy => this.applyGroupBy(groupBy.groupBy));

this.groupBys = [];

return this;
}

/**
* Set the order by.
*
Expand Down

0 comments on commit 3fad91a

Please sign in to comment.