xp-forge/aggregate

v1.1.0 2024-03-24 10:18 UTC

This package is auto-updated.

Last update: 2024-11-24 11:43:26 UTC


README

Build status on GitHub XP Framework Module BSD Licence Requires PHP 7.0+ Supports PHP 8.0+ Latest Stable Version

Circumvents n + 1-problems often occuring with SQL queries.

Example

The following shows how the Aggregate class works, firing only two SQL queries instead of creating an n + 1-problem.

use util\data\Aggregate;
use rdbms\DriverManager;

$conn= DriverManager::getConnection($dsn);
$posts= Aggregate::of($conn->query('select * from post'))
  ->collect('comments', ['id' => 'post_id'], function($ids) use($conn) {
    return $conn->query('select * from comment where post_id in (%d)', $ids);
  })
  ->all()
;

// [
//   [
//     'id'       => 1,
//     'body'     => 'The first post',
//     'comments' => [
//        ['id' => 1, 'post_id' => 1, 'body' => 'Re #1: The first post'],
//        ['id' => 2, 'post_id' => 1, 'body' => 'Re #2: The first post'],
//     ]
//   ],
//   [
//     'id'       => 2,
//     'body'     => 'The second post',
//     'comments' => [
//        ['id' => 3, 'post_id' => 2, 'body' => 'Re #1: The second post'],
//     ]
//   ],
// ]