Having
The having key filters grouped results
using aggregate conditions such as SUM, AVG,
COUNT, MIN, and MAX.
It behaves like a post-grouping WHERE clause.
Purpose
The having clause allows filtering groups after aggregation.
While where filters rows before grouping,
having filters the grouped results using aggregate-based conditions.
Important Notes
- by is always required.
wherefilters before grouping;havingfilters after grouping.- The shape of
havingmirrors the aggregate keys you provide. - Operators are the same as
where:gt,gte,lt,lte,equals,in, etc. orderBy,take, andskipstill work after grouping.
Basic Example
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$result = $prisma->user->groupBy([
'by' => ['country'],
'_sum' => ['profileViews' => true],
'having' => [
'_sum' => [
'profileViews' => ['gt' => 1000] // Only groups where SUM(profileViews) > 1000
]
]
]);
echo "<pre>" . print_r($result, true) . "</pre>";
Complex Example (AVG inside having)
use Lib\Prisma\Classes\Prisma;
$prisma = Prisma::getInstance();
$groups = $prisma->user->groupBy([
'by' => ['country'],
'_avg' => ['profileViews' => true],
'_count' => ['id' => true],
'where' => [
'email' => ['contains' => 'prisma.io'],
],
'having' => [
'_avg' => [
'profileViews' => ['gt' => 100]
],
'_count' => [
'id' => ['gte' => 10]
]
],
'orderBy' => ['country' => 'asc']
]);
echo "<pre>" . print_r($groups, true) . "</pre>";
Shape of having
having['_sum']['field'] => ['gt' => 100]
having['_avg']['price'] => ['lte' => 50]
having['_count']['id'] => ['gte' => 5]