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;
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:
....
....
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.
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.
The results are already in a nested tree. The
PersistentCollectioncan be iterated as if it was an array:Still you should try
$privileges = $q->getArrayResult();and see if that gives a result you would prefer.