Doctrine 2 嵌套集 - 在单个查询中检索完整树

Jam*_*ley 5 nested-sets doctrine-orm doctrine-extensions stofdoctrineextensions

我正在使用stof/StofDoctrineExtensionsBundleAtlantic18/DoctrineExtensions 的捆绑包装器)来实现嵌套集(树)实体。该实体已配置并正常工作,但我无法弄清楚如何在单个查询中检索所有子项(完整树)的所有根音符。我目前有完整的集合返回,但它延迟加载所有子项,这意味着执行了大量查询。

谢谢你的帮助。

小智 3

找到了解决方案。

  1. 检索节点对象的完整列表:

    $repo = $this->getDoctrine()->getManager()->getRepository('NestedEntity');
    $nodes = $repo->getChildren();
    
    Run Code Online (Sandbox Code Playgroud)
  2. 用你的节点构建树。

    $tree = $repo->getRepoUtils()->buildTreeArray($nodes);
    
    Run Code Online (Sandbox Code Playgroud)
  3. buildTreeArray 方法接受节点数组的数组,因此您必须在实体中实现 ArrayAccess 接口。它还将所有子节点放入__children节点数组的键中。

    /**
     * @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 = [];
    
         ...
    
    Run Code Online (Sandbox Code Playgroud)