havingTyped
Description
havingTyped sets a HAVING condition on an aggregate of an entity property: havingTyped('COUNT', user => user.images.id, '>=', 2) gives HAVING COUNT("images"."id") >= :having_…. andHavingTyped and orHavingTyped add to it.
Signature
havingTyped(
aggregate: 'COUNT' | 'COUNT DISTINCT' | 'SUM' | 'AVG' | 'MIN' | 'MAX',
selection: KeyProxyCallback<Entity> | '*',
condition: string,
params?: unknown,
options?: { addValue?: boolean }
): SelectQueryBuilder<Entity>
andHavingTyped(aggregate, selection, condition, params?, options?): SelectQueryBuilder<Entity>
orHavingTyped(aggregate, selection, condition, params?, options?): SelectQueryBuilder<Entity>
Arguments
- aggregate: the aggregate function.
'COUNT DISTINCT'isCOUNT(DISTINCT column). Anything else throws aTypeError: it goes into the SQL. - selection: KeyProxyCallback<Entity> of one column, or
'*'forCOUNT(*), every row of the group (only with'COUNT'). The callback starts at the entity, or at the root set withtyped<Root>(). Columns of joined relations work, and paths into JSON columns as in whereTyped: cast to a number forSUM/AVG, and forMIN/MAXto the type of the value they are compared with. A relation as a whole (user => user.images) is no column and doesn't compile. The types don't restrictSUM/AVGto number columns, since adecimalcolumn is typed as astring:SUMof a text column fails on PostgreSQL and gives 0 on MySQL and SQLite. - condition, params, options: as in whereTyped: the value gets a placeholder of its own unless the condition names a key of
params.
With strictParams the value is checked: a number for COUNT, COUNT DISTINCT, SUM and AVG, the column's value for MIN and MAX.
Like TypeORM's having, havingTyped replaces previously set HAVING conditions.
Usage
// same as `query.having('COUNT(images.id) >= :count', { count: 2 })`
query
.leftJoin('user.images', 'images')
.groupBy('user.id')
.havingTyped('COUNT', user => user.images.id, '>=', 2)
// HAVING COUNT(*) > :having_… AND MAX("order"."createdAt") < :andHaving_…
query
.havingTyped('COUNT', '*', '>', 5)
.andHavingTyped('MAX', order => order.createdAt, '<', since)
// HAVING COUNT(DISTINCT "ticket"."userId") = :groupSize
query.havingTyped('COUNT DISTINCT', ticket => ticket.userId, '= :groupSize', { groupSize: userIds.length })