Question

I have variable $path which contains the array of the names of sibling categories. Using this variable I would like to create a new array $categories_children, that would contain the array of children of each category from $path array according to its title. I'm using Doctrine Tree-Nestedset extension by Gediminas Morkevicius and I've tried this:

    $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);
    }

The problem is that method getChildren() with argument $parent returns the same array as like when the passed argument is NULL. That means it will return all nodes starting with root, instead of starting with selected category. Somehow method findOneByTitle(), which is being used in $parent variable, doesn't accept arguments from getPath() and behaves as NULL.

Was it helpful?

Solution

getChildren $parent argument specify only from which root element get the tree. You can see code of childrenQueryBuilder function in NestedTreeRepository.

To fetch all childs I use own function in repository.

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())
    ;

    ...
}   

If you only need direct childs simplets way to specify childs field in entity

/**
 * @ORM\OneToMany(targetEntity="AbstractTreeNode", mappedBy="parent", fetch="EXTRA_LAZY")
 * @ORM\OrderBy({"lft" = "ASC"})
 */
protected $childs;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top