Permalink
Browse files

feat(querybuilder): Added `groupBy` clause

  • Loading branch information...
Rawphs
Rawphs committed Oct 27, 2016
1 parent b36adf3 commit 3fad91a2598e0983a66b298c7737db66d3489e61
Showing with 62 additions and 0 deletions.
  1. +5 −0 src/EntityRepository.ts
  2. +57 −0 src/QueryBuilder.ts
@@ -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;
@@ -132,6 +136,7 @@ export class EntityRepository<T> {
export interface FindOptions {
orderBy?: any,
groupBy?: any,
alias?: string,
limit?: number,
offset?: number,
@@ -41,6 +41,11 @@ export class QueryBuilder<T> {
*/
private appliedPrimaryKeys: {[key: string]: string} = {};
/**
* @type {Array}
*/
private groupBys: Array<{groupBy: string | Array<string>}> = [];
/**
* @type {Array}
*/
@@ -325,6 +330,7 @@ export class QueryBuilder<T> {
this.criteria.applyStaged();
this.applySelects();
this.applyOrderBys();
this.applyGroupBys();
this.prepared = true;
@@ -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.
*

0 comments on commit 3fad91a

Please sign in to comment.