-
Notifications
You must be signed in to change notification settings - Fork 475
Description
I have a 360-node tree with N degrees of depth. The tree (represented by a model called TreeNode
) will be accessed frequently, but altered very infrequently.
I'm trying to build output similar to the following, in order to build a select dropdown of similar structure.
Product
Product > Category A
Product > Category A > Subcategory 1
Product > Category A > Subcategory 2
Product > Category B
Product > Category C
Product > Category C > Subcategory 1
Product > Category C > Subcategory 1 > Subcategory (a)
Product > Category D
Product > Category D > Subcategory 1
Product > Category D > Subcategory 2
...
In order to do this, I have created a method in my TreeNode
model called getPath()
:
public function getPath() {
$ancestors = $this->getAncestors(['Name']);
return implode(' > ',array_merge(array_column($ancestors->toArray(),'Name'),array($this->Name)));
}
Then I iterate over the results of a TreeNode::all()
and call getPath()
for each one.
@foreach( TreeNode::all() as $node )
{{ $node->getPath() }}<br />
@endforeach
Although the correct output is produced, the problem here is that this method takes 360 database queries build this tree, and if the list of nodes grows the problem will only compound. I have a feeling I'm doing this wrong, but looking through the code for laravel-nestedset
I haven't been able to find an alternative way to build the entire tree.
Is there a more efficient way to do this?
Thanks