laravel-nestedset
laravel-nestedset copied to clipboard
Tree with max depth
Hi, I was wondering if there's a possibility we could implement a feature where we could get a tree with max depth. The issue I have is while building comments I don't want to have an endless tree, reply on reply on reply, and so on, but instead a max depth constraint. I'll try to explain it with an example.
If we have a table like this:
id | parent_id | left | right |
---|---|---|---|
1 | null | 1 | 8 |
2 | 1 | 2 | 7 |
3 | 2 | 3 | 6 |
4 | 3 | 4 | 5 |
$nodeCollection->toTree()
would generate:
1 - 2 - - 3 - - - 4
If we put a max depth constrain of, let's say 1, we would get a tree like this:
1 - 2 - 3 - 4
For max depth of 2:
1 - 2 - - 3 - - 4
and so on, you get the point.
The parent_id
would still point to the original row, but we could have a virtual_parent_id
attribute where it would point to a row considering the max depth constraint.
I have a MySQL query in my mind that would calculate virtual_parent_id
for a row. And then, like in the toTree()
method we would generate a collection, grouping models by virtual_parent_id
instead of parent_id
.
Is this something that could be achieved in this package and is somebody willing to code it. But let's have a discussion anyway, I'll post the query later, and even if nothing comes out of it, maybe I'll write a package of my own.
That's the first thing I've tried to code. You should retrieve your node adding withDepth
:
Category::withDepth()->first()
and use that method
public function getDescendantsByLevel($level = 1)
{
if(!isset($this->depth)) {
throw new \Exception("No depth available, can't find given level descendants");
}
return $this->descendants()->withDepth()->having('depth', '=', $this->depth + $level)->get();
}