xp-forge / aggregate
Data aggregation
v1.1.0
2024-03-24 10:18 UTC
Requires
- php: >=7.0.0
- xp-framework/core: ^12.0 | 11.0 | ^10.0 | ^9.0 | ^8.0
Requires (Dev)
- xp-framework/test: ^2.0 | ^1.0
This package is auto-updated.
Last update: 2024-11-24 11:43:26 UTC
README
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'], // ] // ], // ]