Skip to content

xp-forge/aggregate

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Aggregate data on lists

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'],
//     ]
//   ],
// ]