Download the PHP package val/one-to-many-iterator without Composer
On this page you can find all versions of the php package val/one-to-many-iterator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download val/one-to-many-iterator
More information about val/one-to-many-iterator
Files in val/one-to-many-iterator
Package one-to-many-iterator
Short Description Helper iterator and generator for one-to-many joins
License Unlicense
Homepage https://github.com/valeriangalliat/php-one-to-many-iterator
Informations about the package one-to-many-iterator
One-to-many iterator
Helper iterator and generator for one-to-many joins.
Overview
When you want to fetch a one-to-many relation, you're probably using
a JOIN
to avoid the N+1 selects problem.
Though, it may be difficult to iterate over the result, especially when you need the whole "many" part of the relation loaded for a process.
This is why I created this tiny library. It takes a Traversable
of arrays, having a common key to distinguish the "one" part of the
one-to-many relation, and sorted on this key (so it can yield items
in streaming, without loading the whole set in memory).
It will then aggregate the "many" part of the relation in a configurable key.
Installation
Examples
Your database result iterator, once converted into an array, looks like
this (a typical JOIN
):
But you'd like to iterate over something like this:
To achieve this, just pass your database result to
Val\Iterator\OneToManyIterator
or Val\Iterator\OneToManyGenerator
,
while configuring the common key (here, id
), and aggregate key (here,
children
).
Assuming $result
contains the raw SQL result iterator:
The difference between the iterator and the generator, is, well.. that the former implements a raw PHP iterator while the latter uses a PHP generator (available since version 5.5).
Bugs
- When using a
LEFT JOIN
instead of aJOIN
, thus not guaranteeing the presence of at least one relation item, the aggregate field will still contain one item ofnull
values.