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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With