Answer the question
In order to leave comments, you need to log in
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');
}
$category = Category::with('childrenCategories')->find($request->input('id'));
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;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question