I have simple database table which implements tree structure via parent_id attribute. Something like this:
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
| 1 | test | null |
+----+------+-----------+
| 2 | tes2 | 1 |
+----+------+-----------+
| 3 | tes3 | 2 |
+----+------+-----------+
| 4 | tst | 2 |
+----+------+-----------+
I want to obtain PHP object with tree structure. So object Category will have property subcategories, which will be list of Category objects and so on. I want to obtain this object directly from PostgreSQL database via recursive sql query with Pomm. The goal is not to traverse obtained data and build such object in PHP. I want straight process PostreSQL -> Pomm -> Object.
As for now, I get what I want by only in first level. So first level Category has subcategories, which is list of Category entities. However next level (depth 2) has no subcatogories.
So far I have this:
$sql = <<<SQL
with recursive
cat as (select c.* FROM :category c where parent_id is null),
subcat as (
select c.* from :category c join cat on c.parent_id=cat.id
union all
select c.* from :category c join subcat on c.parent_id=subcat.id
)
select :projection from cat cc, subcat
where cc.id=subcat.parent_id
group by :group_fields
SQL;
$projection = $this->createProjection()
->setField('subcategories', 'array_agg(subcat)', 'public.category[]');
$sql = strtr($sql, [
':category' => $this->structure->getRelation(),
':projection' => $projection->formatFieldsWithFieldAlias('cc'),
':group_fields' => $this->createProjection()->formatFields('cc'),
]);
My question if this is possible with Pomm and if yes, how?