Method Documentation: aggregate

Purpose

The aggregate method is designed for advanced statistical analysis your 'Model' table. It supports a variety of aggregate operations such as AVG, COUNT, MAX, MIN, and SUM. This functionality allows for complex data analysis and reporting, accommodating a range of criteria to refine results.

Parameters

  • array $operation - Defines the aggregate operations and conditions. This parameter should be an associative array containing keys like '_avg', '_count', '_max', '_min', '_sum', 'cursor', 'orderBy', 'skip', 'take', 'where', each specifying the corresponding operation or query modifier.
  • bool $format = false- Optional. Specifies the format of the returned data ('false' or 'true') by default is array, but can also be set to 'true' for object format.

Return Value

The method returns an associative array or an object (based on the $format parameter) containing the results of the specified aggregate operations. Each key in the array/object corresponds to an operation-field pair, and the value is the result of the aggregate function.

Error Handling

Throws an \Exception if the input parameters are not properly formatted as an associative array or if no valid aggregate function is specified. This ensures the method's integrity by preventing invalid operations and signaling potential issues to the developer.

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>";

Advance Example Usage

  use Lib\Prisma\Classes\Prisma;

    $prisma = Prisma::getInstance();
    $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>";