Skip to content

Aggregate & Group

The following uses the module test-vona as an example to explain the usage of aggregate and group

count

typescript
class ServicePost {
  async count() {
    return await this.scope.model.post.count();
  }
}
  • Params
NameDescription
columnThe column to be counted
distinctWhether to enable distinct
whereConditional statement
joinsRelated tables

Aggregate

typescript
class ServicePost {
  async aggregate() {
    const result = await this.scope.model.post.aggregate({
      aggrs: {
        count: ['*', 'stars'],
        sum: 'stars',
        avg: 'stars',
        min: 'stars',
        max: 'stars',
      },
    });
    return result;
  }
}

Vona ORM automatically infers the type of result from the aggrs parameter

  • Params
NameDescription
aggrsThe functions and columns to be aggregated. Functions: count/sum/avg/min/max. Columns: string/string[]
distinctWhether to enable distinct
whereConditional statement
joinsRelated tables

Group

typescript
class ServicePost {
  async group() {
    const result = await this.scope.model.post.group({
      groups: 'userId',
      aggrs: {
        count: '*',
        sum: 'stars',
      },
    });
    return result;
  }
}

Vona ORM automatically infers the type of result from the parameters groups and aggrs

  • Params
NameDescription
groupsThe groups to be grouped: string/string[]
columnsThe group columns to be displayed. If it is empty, the columns specified by the groups parameter will be displayed
aggrsThe functions and columns to be aggregated. Functions: count/sum/avg/min/max. Columns: string/string[]
distinctWhether to enable distinct
whereConditional statement
joinsRelated tables
limitLimit the range of data to be grouped
offsetLimit the range of data to be grouped
havingFilter the group results
ordersSort the group results

Example: having

typescript
class ServicePost {
  async group() {
    const result = await this.scope.model.post.group({
      groups: 'userId',
      aggrs: {
        count: '*',
        sum: 'stars',
      },
      having: {
        count_all: {
          _gt_: 20,
        },
        sum_stars: {
          _gt_: 30,
          _lt_: 50,
        },
      },
    });
    return result;
  }
}

Example: orders

typescript
class ServicePost {
  async group() {
    const result = await this.scope.model.post.group({
      groups: 'userId',
      aggrs: {
        count: '*',
        sum: 'stars',
      },
      orders: [['count_all', 'desc']],
    });
    return result;
  }
}

Released under the MIT License.