Monday, February 27, 2017

How to merge Laravel's Baum hierarchy trees into a single tree?

I'm using Laravel 5.1 and etrepat/baum package for implementing nested sets on my Category model.

I've a collection of categories, for each one I get their ancestor's hierarchy tree like this:

$category->getAncestorsAndSelf()->toHierarchy();

For example, let's say I have 4 categories: Category C, Category D, Category E and Category F. And each tree looks like this:

  • Category A
    • Category B
      • Category C
  • Category A
    • Category B
      • Category D
  • Category A
    • Category B
      • Category C
        • Category E
  • Category A
    • Category F

I'm trying to merge them into one tree like this:

  • Category A
    • Category B
      • Category C
        • Category E
      • Category D
    • Category F

So far I've tried the merge() function and a custom recursive function with no luck, I always end up with duplicates.



via Camilo

Advertisement