且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Magento 中的类别(包括其子类别)中获取所有产品?

更新时间:2023-01-30 07:37:59

我通过在产品集合模型中实现 addCategoriesFilter 解决了这个问题,这里是补丁.将修改后的代码复制到 local 池以允许更新到较新版本.

I've solved this problem by implementing addCategoriesFilter in product collection model, here is the patch. Modified code to be copied to the local pool to allow updates to a newer version.

@@ -103,6 +103,7 @@
      * Allowed filters
      *  store_id                int;
      *  category_id             int;
+     *  category_ids            array;
      *  category_is_anchor      int;
      *  visibility              array|int;
      *  website_ids             array|int;
@@ -567,6 +568,21 @@
     }

     /**
+     * Specify categories filter for product collection
+     *
+     * @param array $categories
+     * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
+     */
+    public function addCategoriesFilter(array $categories)
+    {
+        $this->_productLimitationFilters['category_ids'] = $categories;
+
+        ($this->getStoreId() == 0)? $this->_applyZeroStoreProductLimitations() : $this->_applyProductLimitations();
+
+        return $this;
+    }
+
+    /**
      * Join minimal price attribute to result
      *
      * @return Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
@@ -1592,7 +1608,7 @@
         $this->_productLimitationJoinPrice();
         $filters = $this->_productLimitationFilters;

-        if (!isset($filters['category_id']) && !isset($filters['visibility'])) {
+        if (!isset($filters['category_id']) && !isset($filters['category_ids']) && !isset($filters['visibility'])) {
             return $this;
         }

@@ -1604,11 +1620,16 @@
             $conditions[] = $this->getConnection()
                 ->quoteInto('cat_index.visibility IN(?)', $filters['visibility']);
         }
-        $conditions[] = $this->getConnection()
-            ->quoteInto('cat_index.category_id=?', $filters['category_id']);
-        if (isset($filters['category_is_anchor'])) {
+
+        if (!isset($filters['category_ids'])) {
             $conditions[] = $this->getConnection()
-                ->quoteInto('cat_index.is_parent=?', $filters['category_is_anchor']);
+                ->quoteInto('cat_index.category_id=?', $filters['category_id']);
+            if (isset($filters['category_is_anchor'])) {
+                $conditions[] = $this->getConnection()
+                    ->quoteInto('cat_index.is_parent=?', $filters['category_is_anchor']);
+            }
+        } else {
+            $conditions[] = $this->getConnection()->quoteInto('cat_index.category_id IN(' . implode(',', $filters['category_ids']) . ')', "");
         }

         $joinCond = join(' AND ', $conditions);

用法:

$category = $layer->getCurrentCategory();
$categories = $category->getAllChildren(true);

$collection = Mage::getResourceModel('catalog/product_collection');
$collection->addCategoriesFilter($categories);