laravel-nestedset icon indicating copy to clipboard operation
laravel-nestedset copied to clipboard

question: flatten collection of categories with descendants?

Open wivaku opened this issue 4 years ago • 0 comments

Perhaps similar to #409

I have a search method that returns categories with descendants. I want to flatten the result.

E.g. \App\Models\Category::search('movie')

=> Kalnoy\Nestedset\Collection {#4852
     all: [
       App\Models\Category {#4874
         id: 22,
         _lft: 42,
         _rgt: 49,
         parent_id: 1,
         name: "Movie Theater",
         descendants: Kalnoy\Nestedset\Collection {#4830
           all: [
             App\Models\Category {#4878
               id: 23,
               _lft: 43,
               _rgt: 44,
               parent_id: 22,
               name: "Drive-in Theater",
             },
             App\Models\Category {#4900
               id: 24,
               _lft: 45,
               _rgt: 46,
               parent_id: 22,
               name: "Indie Movie Theater",
             },
             App\Models\Category {#4760
               id: 25,
               _lft: 47,
               _rgt: 48,
               parent_id: 22,
               name: "Multiplex",
             },
           ],
         },
       },
       App\Models\Category {#4793
         id: 24,
         _lft: 45,
         _rgt: 46,
         parent_id: 22,
         name: "Indie Movie Theater",
         descendants: Kalnoy\Nestedset\Collection {#4832
           all: [],
         },
       },
     ],
   }

Would like to get a collection of Categories like: collect(Category 22, Category 23, Category 24, Category 25, Category 24) (and then I will get the unique values of that collection)

This ones does the trick, but I was hoping there is an official / better way of doing it.

>>> \App\Models\Category::search('movie')
  ->map(fn($e) => $e->descendants->prepend($e))
  ->flatten()
  ->map(function($e) { unset($e->descendants); return $e; })

=> Illuminate\Support\Collection {#4949
     all: [
       App\Models\Category {#4874
         id: 22,
         _lft: 42,
         _rgt: 49,
         parent_id: 1,
         name: "Movie Theater",
       },
       App\Models\Category {#4937
         id: 23,
         _lft: 43,
         _rgt: 44,
         parent_id: 22,
         name: "Drive-in Theater",
       },
       App\Models\Category {#4944
         id: 24,
         _lft: 45,
         _rgt: 46,
         parent_id: 22,
         name: "Indie Movie Theater",
       },
       App\Models\Category {#4936
         id: 25,
         _lft: 47,
         _rgt: 48,
         parent_id: 22,
         name: "Multiplex",
       },
       App\Models\Category {#4945
         id: 24,
         _lft: 45,
         _rgt: 46,
         parent_id: 22,
         name: "Indie Movie Theater",
       },
     ],
   }

wivaku avatar May 03 '21 09:05 wivaku