5

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.

James Crinkley
  • 1,398
  • 1
  • 13
  • 33

2 Answers2

4

You can just use childrenHierarchy() method for whole tree retrieve:

$tree = $repo->childrenHierarchy();  
vp_arth
  • 14,461
  • 4
  • 37
  • 66
3

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 = [];
    
         ...
    
user2554865
  • 365
  • 1
  • 9