Group By
The groupBy method groups records
by one or more fields and allows applying aggregate operations on each group.
Purpose
The groupBy method is used to generate grouped data summaries, statistics, or reports.
It supports grouping by one or more fields and applying aggregates like
_count, _avg, _sum, _min, and _max.
Important Notes
- The by key is required. It defines the field(s) used to group the records.
- You can group by a single field using a string or by multiple fields using an array.
- Aggregation fields must reference scalar fields only.
Basic Example
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$users = $prisma->user->groupBy([
'by' => 'country',
]);
echo "<pre>";
echo "Users grouped by country: " . print_r($users, true);
echo "</pre>";
Example With Conditions & Aggregations
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$users = $prisma->user->groupBy([
'by' => 'country',
'where' => [
'email' => [
'contains' => 'example.com'
]
],
'orderBy' => ['name'],
'_count' => ['email' => true],
'_max' => ['email' => true],
'_min' => ['email' => true],
]);
echo "<pre>";
echo "Users grouped by country: " . print_r($users, true);
echo "</pre>";