@@ -337,10 +337,44 @@ public function loadProductCount($items, $countRegular = true, $countAnchor = tr
337337 $ categoryIds = array_keys ($ anchor );
338338 $ countSelect = $ this ->getProductsCountQuery ($ categoryIds , (bool )$ websiteId );
339339 $ categoryProductsCount = $ this ->_conn ->fetchPairs ($ countSelect );
340+
341+ $ subSelect = clone $ this ->_conn ->select ();
342+ $ subSelect ->from (['ce2 ' => $ this ->getTable ('catalog_category_entity ' )], 'ce2.entity_id ' )
343+ ->where ("ce2.path LIKE CONCAT(ce.path, '/%') " );
344+
345+ $ select = clone $ this ->_conn ->select ();
346+ $ select ->from (['ce ' => $ this ->getTable (
347+ 'catalog_category_entity ' )],
348+ 'ce.entity_id '
349+ );
350+ $ joinCondition = new \Zend_Db_Expr ("ce.entity_id=cp.category_id OR cp.category_id IN ( {$ subSelect }) " );
351+ $ select ->joinLeft ([
352+ 'cp ' => $ this ->getProductTable ()],
353+ $ joinCondition ,
354+ 'COUNT(DISTINCT cp.product_id) AS product_count '
355+ );
356+ if ($ websiteId ) {
357+ $ select ->join (
358+ ['w ' => $ this ->getProductWebsiteTable ()],
359+ 'cp.product_id = w.product_id ' ,
360+ []
361+ )->where (
362+ 'w.website_id = ? ' ,
363+ $ websiteId
364+ );
365+ }
366+ $ select ->where ('ce.entity_id IN(?) ' , $ categoryIds );
367+ $ select ->group ('ce.entity_id ' );
368+
369+ $ countFromCategoryTable = $ this ->_conn ->fetchPairs ($ select );
370+
340371 foreach ($ anchor as $ item ) {
341- $ productsCount = isset ($ categoryProductsCount [$ item ->getId ()])
342- ? (int )$ categoryProductsCount [$ item ->getId ()]
343- : $ this ->getProductsCountFromCategoryTable ($ item , $ websiteId );
372+ $ productsCount = 0 ;
373+ if (isset ($ categoryProductsCount [$ item ->getId ()])) {
374+ $ productsCount = (int )$ categoryProductsCount [$ item ->getId ()];
375+ } elseif (isset ($ countFromCategoryTable [$ item ->getId ()])) {
376+ $ productsCount = (int )$ countFromCategoryTable [$ item ->getId ()];
377+ }
344378 $ item ->setProductCount ($ productsCount );
345379 }
346380 }
0 commit comments