0

我有變量$ path,其中包含兄弟類別的名稱數組。使用這個變量,我想創建一個新的數組$ categories_children,根據它的標題包含$ path數組中每個類別的子數組。我使用Doctrine Tree-Nestedset延伸通過格迪米納斯Morkevicius,我已經試過這樣:Symfony 2中的學說樹路徑迭代

$em = $this->getDoctrine()->getManager(); 
    $repo = $em->getRepository('MyProjectAdminBundle:Category'); 

    $category = $repo->findOneById($id);  
    $path = $repo->getPath($category); 

    $categories_children = array(); 

    foreach($path as $node){ 
     $parent = $repo->findOneByTitle($node); 
     $categories_children[] = $repo->getChildren($parent, true); 
    } 

的問題是方法的getChildren()的參數$父返回同一陣列像時所傳遞的參數爲NULL。這意味着它將返回以root開頭的所有節點,而不是以選定的類別開始。不知何故,在$ parent變量中使用的方法findOneByTitle()不接受來自getPath()的參數並且行爲爲NULL。

回答

0

getChildren $ parent參數僅指定從哪個根元素獲取樹。您可以在NestedTreeRepository中看到childrenQueryBuilder函數的代碼。

要獲取所有孩子,我在資源庫中使用自己的函數。

public function getTreeAsFlatArray(AbstractTreeNode $parent = null, array $options = array()) { 
    $qb = $this->createQueryBuilder('node');  
    $qb 
     ->andWhere('node.lft > :parent_lft') 
      ->setParameter('parent_lft', $parent->getLft()) 
     ->andWhere('node.lft < :parent_rgt') 
      ->setParameter('parent_rgt', $parent->getRgt()) 
     ->andWhere('node.level <= :level') 
      ->setParameter('level', $parent->getLevel() + $o['depth']) 
     ->andWhere('node.root = :root') 
      ->setParameter('root', $parent->getRoot()) 
    ; 

    ... 
} 

如果你只需要直接孩子的simplets方式在實體指定孩子的領域

/** 
* @ORM\OneToMany(targetEntity="AbstractTreeNode", mappedBy="parent", fetch="EXTRA_LAZY") 
* @ORM\OrderBy({"lft" = "ASC"}) 
*/ 
protected $childs; 
+0

現在,當我使用getTreeAsFlatArray($父),則返回「FatalErrorException:錯誤:調用一個成員函數getLft ()在一個非對象「。 –

+0

它只是一個示例查詢如何獲取節點的孩子,節點準備好使用函數。 –

+0

好吧,我會調整getTreeAsFlatArray()只是爲了我的用法。我也試圖在實體中使用get方法來使用childs字段。爲了獲取孩子,我簡單地使用了$ categories_children [] = $ repo-> getChilds()。但結果仍然相同:「錯誤:調用一個非對象的成員函數getChilds()。」我不明白,怎麼可以方法findOneByTitle()返回別的東西比對象。謝謝。 –