Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter doctrine nested set tree children hierarchy

I am using a doctrine nested set tree in my application.

I can easily retrieve the whole tree using

        $repo->childrenHierarchy(
            null, /* starting from root nodes */
            false, /* false: load all children, true: only direct */
            $options
        )

What I want though is to filter entities of this tree according to a foreign key (categories belong to users so each category has a userId)

Unfortunately the option that accepts a callback to filter on the node does not allow filtering on a foreign key, foreign keys values are not included in the node array :

    $options = array(
        'decorate'  => true,
        'rootOpen'  => '<ul>',
        'rootClose' => '</ul>',
        'childOpen' =>  function ($node) use($user) {
            // $node does not contain any foreign key
            if ($node['userId'] != $user->getId()) {
                return null;
            }
            return "<li id='".$node['id']."'>";
        },
        'childClose' => '</li>',
    );

How can I solve this issue ?

like image 949
Sébastien Avatar asked Dec 07 '25 06:12

Sébastien


1 Answers

I finally found the solution, you have to create a new custom method in the repository of the entity and extend the original queryBuilder with your own filters like so:

public function getTree()
{
    $qb = $this->getNodesHierarchyQueryBuilder();
    $qb
        ->andWhere('node.status = :status')
        ->setParameter('status', 1)
        ->andWhere('node.deletedAt IS NULL')
    ;

    $aComponents = $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);

    return $this->buildTreeArray($aComponents);
}

At the end, you call the method buildTreeArray in order to create the tree structure.

like image 84
Arnaud Ncy Avatar answered Dec 09 '25 01:12

Arnaud Ncy