Skip to content

How to get ancestorsAnd self for multiple records at once ? #251

Answered by staudenmeir
cmendez2121 asked this question in Q&A
Discussion options

You must be logged in to vote

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:

$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();

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@cmendez2121
Comment options

Comment options

You must be logged in to vote
1 reply
@cmendez2121
Comment options

Answer selected by cmendez2121
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants