Circumvents n + 1
-problems often occuring with SQL queries.
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'],
// ]
// ],
// ]