コード例 #1
0
 /**
  * @param Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection $productCollection
  * @param $categoryCollection
  * @param bool $inCurrentCategory
  * @return $this
  */
 public function addCountToCategories($productCollection, $categoryCollection, $inCurrentCategory = false)
 {
     Mana_Core_Profiler2::start(__METHOD__);
     $isAnchor = array();
     $isNotAnchor = array();
     foreach ($categoryCollection as $category) {
         if ($category->getIsAnchor()) {
             $isAnchor[] = $category->getId();
         } else {
             $isNotAnchor[] = $category->getId();
         }
     }
     $productCounts = array();
     if ($isAnchor || $isNotAnchor) {
         /* @var $select Varien_Db_Select */
         $select = $productCollection->getProductCountSelect();
         if ($inCurrentCategory) {
             $from = $select->getPart(Varien_Db_Select::FROM);
             if (isset($from['cat_index'])) {
                 $categoryId = $this->getLayer()->getCurrentCategory()->getId();
                 $from['cat_index']['joinCondition'] = preg_replace("/(.*)(`?)cat_index(`?).(`?)category_id(`?)='(\\d+)'(.*)/", "\$1\$2cat_index\$3.\$4category_id\$5='{$categoryId}'\$7", $from['cat_index']['joinCondition']);
                 $select->setPart(Varien_Db_Select::FROM, $from);
             }
         }
         Mage::dispatchEvent('catalog_product_collection_before_add_count_to_categories', array('collection' => $productCollection));
         if ($isAnchor) {
             $anchorStmt = clone $select;
             $anchorStmt->limit();
             //reset limits
             $anchorStmt->where('count_table.category_id IN (?)', $isAnchor);
             $sql = $anchorStmt->__toString();
             $productCounts += $productCollection->getConnection()->fetchPairs($anchorStmt);
             $anchorStmt = null;
         }
         if ($isNotAnchor) {
             $notAnchorStmt = clone $select;
             $notAnchorStmt->limit();
             //reset limits
             $notAnchorStmt->where('count_table.category_id IN (?)', $isNotAnchor);
             $notAnchorStmt->where('count_table.is_parent = 1');
             $productCounts += $productCollection->getConnection()->fetchPairs($notAnchorStmt);
             $notAnchorStmt = null;
         }
         $select = null;
         $productCollection->unsProductCountSelect();
     }
     foreach ($categoryCollection as $category) {
         $_count = 0;
         if (isset($productCounts[$category->getId()])) {
             $_count = $productCounts[$category->getId()];
         }
         $category->setProductCount($_count);
     }
     Mana_Core_Profiler2::stop();
     return $this;
 }