cache->getItem('list_category_'.$category)->isHit()) { return $this->render('productList.html.twig', ['listType' => 'category_'.$category]); } /** @var Product[] $products */ $products = Product::with(['price', 'lowestPrice']) ->selectRaw('products.*') ->distinct('products.id') ->when(!is_null($category) , fn ($q) => $q->whereRaw('json_each.value = ?', [$category])) ->fromRaw('products, json_each(products.categories)') ->orderByDesc('starred') ->orderByDesc('created_by') ->get(); $categoriesTree = []; foreach ($products as $product) { $categoriesTree = $this->addToTree($product->categories, $categoriesTree); } return $this->render('productList.html.twig', ['products' => $products, 'listType' => 'category_' . $category, 'category' => $category, 'categoryTree' => $categoriesTree]); } private function addToTree(array $categories, mixed $categoriesTree) { $tmp = &$categoriesTree; foreach ($categories as $category) { if (empty($tmp[$category])) { $tmp[$category] = ['count' => 0]; } $tmp = &$tmp[$category]; $tmp['count']++; } return $categoriesTree; } }