How to get ancestorsAnd self for multiple records at once ? #251
-
HI i have an issue selecting nodes with Ancestors and make it as a tree estructure 4 and 8 are leaf nodes / records $cuentas = CatCuentas::find([4, 8])->ancestorsAndSelf()->depthFirst()->get(); $cuentas = CatCuentas::whereIn('id',[4,8])->descendantsAndSelf()->get(); and get Method Staudenmeir\LaravelAdjacencyList\Eloquent\Collection::ancestorsAndSelf does not exist. if i do $cuentas = CatCuentas::find(4)->ancestorsAndSelf()->depthFirst()->get(); Works fine for a singe record. Id 4 is leaf.
but its not the desired result , any pointers ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Hi @cmendez2121,
Do you want to get the part of tree that only contains the paths (from root to leaf) of these leaf records? Do these leaf records always lead to the same root node? |
Beta Was this translation helpful? Give feedback.
-
I don't see an elegant solution for this. You need to get the ancestors separately and normalize their depths so that all root nodes have the depth $a = CatCuentas::find(4)->ancestorsAndSelf;
$a = $a->each(fn($model) => $model->depth -= $a->min('depth'));
$b = CatCuentas::find(8)->ancestorsAndSelf;
$b = $b->each(fn($model) => $model->depth -= $b->min('depth'));
$tree = $a->merge($b)->toTree(); |
Beta Was this translation helpful? Give feedback.
I don't see an elegant solution for this.
You need to get the ancestors separately and normalize their depths so that all root nodes have the depth
0
. Then you can merge them into a single tree: