T
T
Tech52020-05-23 18:20:08
Laravel
Tech5, 2020-05-23 18:20:08

How to optimize the display of parent and child categories in the form of a "tree"?

Good day!

Dear Khabrovites, I just started to learn Laravel and faced the problem of OPTIMIZING the output of parent and child categories in the form of a "tree".
It is required to display about forty parent and almost a hundred child categories.

There are two tables categories and subcategories, the last one has a category_id foreign key associated with the id in the categories table. There are also two models: Category and Subcategory with a one-to-many relationship.

In the controller I write:

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::with('subcategory')->get();
        return view('dashboard.categories.index', compact('categories'));
    } 
}


In the blade file I output this:
@foreach($categories as $category)
  {{ $category->title }}

  @foreach($category->subCategory as $sub_category)
    {{ $sub_category->title }}
  @endforeach

@endforeach


In this case, the output of each parent category drops a request to the view base:
select * from `subcategories` where `subcategories`.`category_id` = 1 and `subcategories`.`category_id` is not null


In total, more than 40 requests per page just by displaying this "category tree"!
Using pagination and limits is not an option, combining parent and child categories into one table is also.

Can you please tell me how to optimize the output of parent and child categories?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin B., 2020-05-23
@Tech5

You are messing around somewhere and doing something different than what you write here. Try replacing subcategory with subCategory in the main query

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question