【发布时间】:2015-10-10 23:50:29
【问题描述】:
我有一个简单的数据库表,它通过 parent_id 属性实现树结构。像这样的:
+----+------+-----------+
| id | name | parent_id |
+----+------+-----------+
| 1 | test | null |
+----+------+-----------+
| 2 | tes2 | 1 |
+----+------+-----------+
| 3 | tes3 | 2 |
+----+------+-----------+
| 4 | tst | 2 |
+----+------+-----------+
我想获得具有树形结构的 PHP 对象。因此对象类别将具有属性子类别,这将是类别对象的列表等。我想通过 Pomm 的递归 sql 查询直接从 PostgreSQL 数据库获取这个对象。目标不是遍历获得的数据并在 PHP 中构建这样的对象。我想要直接处理 PostreSQL -> Pomm -> 对象。
就目前而言,我只能在第一级得到我想要的。所以第一级类别有子类别,这是类别实体的列表。但是下一级(深度 2)没有子类别。
到目前为止,我有这个:
$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'),
]);
我的问题是 Pomm 是否可以实现,如果可以,如何实现?
【问题讨论】:
标签: php postgresql pomm