主义2:从自我反省的实体构建一个嵌套的数组树 [英] Doctrine 2: Building a nested array tree from a self-refrencing Entity
问题描述
我有一个实体,如下所示:
I have an Entity that looks like this:
class Privilege
{
/**
* @Id @Column(type="bigint")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @Column(type="string",length=255)
*/
private $name;
/**
* @Column(type="string",length=255)
*/
private $slug;
/**
* @OneToMany(targetEntity="Privilege", mappedBy="parent")
*/
private $children;
/**
* @ManyToOne(targetEntity="Privilege", inversedBy="children")
* @JoinColumn(name="p_id", referencedColumnName="id")
*/
private $parent;
如果特权实体
没有父,该字段为NULL。我有一个这样的基本查询:
If a Privilege Entity
does not have a parent, the field is NULL. I have a basic query like this:
$qb = $this->em->createQueryBuilder()
->select('p')
->from('\Dashboard\Entity\Privilege', 'p')
->andWhere('p.parent IS NULL');
$q = $qb->getQuery();
$privileges = $q->getResult();
我希望从这个方法返回的数组结果看起来类似于这样:
I would like the array result I return from this method to look similar to this:
root1:
child1:
subchild1a
subchild2a
child2:
subchild1b
subchild2b
subchild3b
subsubchild1b
child3:
subchild1c
root2:
....
....
有没有办法HYDRATE从Doctrine 2的结果,所以它以这种方式构建数组结果?如果没有,你将如何构建这个数组?我仍在玩Doctrine 2,我发现我的 $特权中的每个元素都有一个
$ privilege-> getChildren()
返回 PersistentCollection
,显然不是实际记录。
Is there a way to HYDRATE the results from Doctrine 2 so it builds the array results this way? If not, how would you build this array? I am still playing around with Doctrine 2, and I noticed each element in my $privileges
array has a $privilege->getChildren()
which returns a PersistentCollection
, obviously not the actual record.
如果我必须自己构建这个嵌套树(即:在Doctrine中没有内置的方式来做到这一点),我该怎么把这个 PersistentCollection
返回实际的数据,所以我可以建立一些递归方法来为我建立它?我正在查看文档,但显然是在错误的地方。
If I have to build this nested tree myself (ie: no built in way in Doctrine to do it), how do I turn this PersistentCollection
returned into the actual data so I can build some sort of recursive method to build it for me? I am looking through the docs, but obviously in the wrong place.
推荐答案
结果已经在一个嵌套的树中。 PersistentCollection
可以像数组一样迭代:
The results are already in a nested tree. The PersistentCollection
can be iterated as if it was an array:
foreach($parent->getChildren() as $child) {
// $child is an instance of Privilige
}
仍然应该尝试 $ privileges = $ q-> getArrayResult();
,看看是否给出了你喜欢的结果。
Still you should try $privileges = $q->getArrayResult();
and see if that gives a result you would prefer.
这篇关于主义2:从自我反省的实体构建一个嵌套的数组树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!