doctrine-ormnested-setsdoctrine-extensionsstofdoctrineextensions

Doctrine 2 nested set - retrieve full tree in single query


I'm using stof/StofDoctrineExtensionsBundle (Bundle wrapper for Atlantic18/DoctrineExtensions) to implement a Nested Set (tree) entity. The entity is configured and working, but I can't figure out how to retrieve all root notes with all of their children (full trees) in a single query. I currently have the full collection returning however it lazy loads all children, meaning a large number of queries is performed.

Thanks for any help.


Solution

  • Found a solution.

    1. retrieve full list of node objects:

      $repo = $this->getDoctrine()->getManager()->getRepository('NestedEntity');
      $nodes = $repo->getChildren();
      
    2. build tree with your nodes.

      $tree = $repo->getRepoUtils()->buildTreeArray($nodes);
      
    3. buildTreeArray method accepts array of node-arrays, so you must implement ArrayAccess interface in your Entity. Also it puts all children in __children key of node-array.

      /**
       * @Gedmo\Tree(type="nested")
       * @ORM\Table(name="nested_entity")
       * @ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
       */
       class NestedEntity implements \ArrayAccess
       {
      
           public function offsetExists($offset)
           {
               return property_exists($this, $offset);
           }
      
           public function &offsetGet($offset)
           {
               return $this->$offset;
           }
      
           public function offsetSet($offset, $value)
           {
               $this->$offset = $value;
           }
      
           public function offsetUnset($offset)
           {
               $this->$offset = null;
           }
      
           protected $__children = [];
      
           ...