S
S
Sergey Khlopov2020-02-07 14:29:13
Laravel
Sergey Khlopov, 2020-02-07 14:29:13

Is it possible to reduce the number of database queries when getting a category tree?

Hello, please tell me, the nesting of categories provides a key in the database - parent_id,
the model contains the following method:

public function childrenCategories()
{
   return $this->hasMany('App\Models\Admin\Category','parent_id');
}

You need to build a category tree, I get a category like this:
$category = Category::with('childrenCategories')->find($request->input('id'));

And then I output it like this through recursion:
public static function formatCategoryTree($inputData)
    {
        $response = [];
        foreach ($inputData as $category) {
            $response[] = [
                'id' => $category->id,
                'name' => $category->name,
                'children' => ($category->childrenCategories->isNotEmpty()) ?
                    FormattingCategory::formatCategoryTree($category->childrenCategories) : [],
            ];
        }
        return $response;
    }

And for one of the categories, it turns out 18 requests to the database, as I understand it, the deeper the nesting is, the more requests there will be to the database, please tell me how you can reduce the number of requests, thank you in advance for your answer.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-02-07
@Shlop

Try to look towards the Nested Set and this one
https://packagist.org/packages/kalnoy/nestedset

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question