groupBy()

The groupBy() method lets you group query results by one or more fields. It is commonly used with aggregate functions like SUM() or COUNT() and is required when using having(). Multiple calls to groupBy() are supported and cumulative.

Signature:

public function groupBy(string $field): self

Basic Usage

Group results by user ID:

$db->groupBy('user_id');
$stats = $db->get('orders');

Multiple groupBy() calls

You can chain multiple groupings – they will be combined automatically:

$db->groupBy('user_id');
$db->groupBy('year');
$rows = $db->get('orders');

Validation and Rules

  • Only safe field names (alphanumeric + optional dot notation) are allowed.
  • Function calls (e.g. YEAR(date)) are not permitted.
  • Subquery aliases cannot be used here – only direct columns.

See Also