staudenmeir/laravel-adjacency-list

Search/Filter nested list

vatsake opened this issue · 7 comments

Is it possible to search/filter nested items that match a criteria and return from root to the child item?

For example if I have the following data, and I search for "Doe". It should return from 1 to 4 (tree) and excluding item with ID 3.

id parent_id name
1 null John
2 1 Hussein
3 1 Applepie
4 2 Doe

Hi @vatsake,
The only way I see is to find the matching items and then fetch their ancestors:

$items = YourModel::where('name', 'Doe')->with('ancestorsAndSelf')->get();

foreach ($items as $item) {
    $result = $item->ancestorsAndSelf->reverse();
}

Hey

Thanks, that did the trick.
$item->ancestorsAndSelf->toTree();

I don't suppose there's an easy way to also combine duplicate 'parent' elements?
For example if a root has 2 children that has "Doe"

id parent_id name
1 null John
2 1 Hussein
3 1 Doe
4 2 McDoe

Do you want to merge all results into a single tree?

Yeah.

id parent_id name
1 null John
2 1 Hussein
3 1 Doe
4 2 McDoe
5 null Michael
6 5 Doe
7 5 Jackson

The result I'd want:
| John
| - Hussein
| -- McDoe
| - Doe
| Michael
| - Doe

You need to write a recursive method to merge the trees level by level. There's no easier way, unfortunately.

Aight, thanks for the previous tip!

I don't know if you have solved this using your own custom filter function but I solved this using the treeOf and withRecursiveQueryConstraint methods of the package:

image image

The trick is to apply the constraints to the base query and also set the same constraints for the recursive children.