Level 63
I have a similar situation.
Here is my code.
public function categories(): HasMany
{
return $this->hasMany(Category::class)->with('categories')->orderBy('name');
}
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
public function subCategoryIds(): array
{
$subCategoryIds = [$this->id];
foreach ($this->categories as $category) {
$subCategoryIds = array_merge($subCategoryIds, $category->subCategoryIds());
}
return $subCategoryIds;
}
public function subTables(): Collection
{
return Table::with('category')->whereIn('category_id', $this->subCategoryIds())->orderBy('name')->get();
}
public function tables(): HasMany
{
return $this->hasMany(Table::class)->orderBy('name');
}
And I get the categories with the tables in the controller.
public function categories(): Collection
{
return Category::select('id', 'name', 'description', 'category_id')
->with('categories', 'tables')
->whereNull('category_id')
->orderBy('name')
->get();
}
public function tables(): Collection
{
$tables = new Collection;
if ($this->selectedCategory) {
$tables = $this->selectedCategory->subTables();
} else {
$tables = Table::orderBy('name')->get();
}
return $tables;
}
The only problem is that if I have 10 different categories and each one has also 10 subcategories, ... there is a big N+1 problem.
For my project it doesn't matter because there are very few categories, but it can be a problem for a lot of categories.