Aggregate

The aggregate method provides advanced statistical operations such as AVG, COUNT, MAX, MIN, and SUM. It supports extensive filtering, pagination, and ordering options for powerful data analysis.

Purpose

The aggregate method allows performing statistical operations over your model's data. It supports multiple aggregate functions simultaneously and can filter, order, or limit results. This makes it ideal for analytics dashboards, reports, or data summaries.

Parameters

  • $operation — associative array containing _avg, _count, _max, _min, _sum, where, orderBy, cursor, skip, take.

Return Value

Returns an associative array or object containing the aggregate results. Each key corresponds to an aggregate operation and field combination.

Error Handling

Throws an exception if:

  • The parameters are not an associative array.
  • No valid aggregate function is provided.
  • Invalid formatting or unsupported values are passed.

Basic Example Usage

use Lib\Prisma\Classes\Prisma;

$prisma = Prisma::getInstance();
$aggregate = $prisma->user->aggregate([
    '_avg' => [
        'age' => true,
    ],
    '_count' => [
        'age' => true
    ],
    'where' => [
        'email' => [
            'contains' => 'example.com'
        ]
    ],
]);

echo "<pre>";
echo "Aggregate: " . print_r($aggregate, true);
echo "</pre>";

Advanced Example Usage

$aggregate = $prisma->user->aggregate([
    '_avg' => [
        'age' => true,
    ],
    '_count' => [
        'age' => true
    ],
    '_max' => [
        'age' => true
    ],
    '_min' => [
        'age' => true
    ],
    '_sum' => [
        'age' => true
    ],
    'where' => [
        'email' => [
            'contains' => 'example.com'
        ]
    ],
    'take' => 3,
    'skip' => 1,
    'cursor' => [
        'id' => '82KX1Y7EO21ee9OFSQee1'
    ]
]);

echo "<pre>";
echo "Aggregate: " . print_r($aggregate, true);
echo "</pre>";