Permalink
Browse files

feat(querybuilder): Added `.having()`

  • Loading branch information...
Rawphs authored and RWOverdijk committed Oct 31, 2016
1 parent befa3e6 commit eab19c0935491e98758156d393e04a7d89f25187
Showing with 44 additions and 9 deletions.
  1. +8 −3 src/Criteria.ts
  2. +36 −6 src/QueryBuilder.ts
@@ -120,13 +120,18 @@ export class Criteria {
* @return Criteria
*/
public apply(criteria: Object, statement?: knex.QueryBuilder, parentKey?: string, parentKnexMethodName?: string): Criteria {
statement = statement || this.statement;
statement = statement || this.statement;
parentKnexMethodName = parentKnexMethodName || criteria['method'];
Object.keys(criteria).forEach(key => {
if (key === 'method') {
return;
}
let value = criteria[key];
if (!(value === null || typeof value !== 'object') && value.constructor === Object) {
return this.apply(value, statement, key);
return this.apply(value, statement, key, parentKnexMethodName);
}
if (this.operatorKnexMethod[key]) {
@@ -146,7 +151,7 @@ export class Criteria {
key = this.mapToColumn(parentKey || key);
return statement[parentKnexMethodName || 'where'](key, operator, value);
return statement[parentKnexMethodName](key, operator, value);
});
return this;
@@ -373,13 +373,18 @@ export class QueryBuilder<T> {
}
// Support select functions. Don't add to hydrator, as they aren't part of the entities.
Object.getOwnPropertyNames(propertyAlias).forEach(selectFunction => {
if (this.functions.indexOf(selectFunction) === -1) {
throw new Error(`Unknown function "${selectFunction}" specified.`);
}
let select = Object.getOwnPropertyNames(propertyAlias);
let selectFunction = select[0];
let selectAlias = propertyAlias[select[1]];
let fieldName = this.criteria.mapToColumn(propertyAlias[select[0]]);
this.statement[selectFunction](this.criteria.mapToColumn(propertyAlias[selectFunction]));
});
if (this.functions.indexOf(selectFunction) === -1) {
throw new Error(`Unknown function "${selectFunction}" specified.`);
}
select.length > 1
? this.statement[selectFunction](`${fieldName} as ${selectAlias}`)
: this.statement[selectFunction](fieldName);
return this;
}
@@ -636,6 +641,31 @@ export class QueryBuilder<T> {
return this;
}
criteria['method'] = 'where';
this.criteria.stage(criteria);
this.prepared = false;
return this;
}
/**
* Sets the having clause.
*
* .having({})
*
* @param {{}} criteria
*
* @returns {QueryBuilder}
*/
public having(criteria: Object): this {
if (!Object.getOwnPropertyNames(criteria).length) {
return this;
}
criteria['method'] = 'having';
this.criteria.stage(criteria);
this.prepared = false;

0 comments on commit eab19c0

Please sign in to comment.