开发者

How to get all product from a category including its subcategories in Magento?

I'm looking for a way to retrieve all products from a category includings its subcategories and return me a Product Collection.

I know I can iterate over categories to get ids of product and load them in开发者_JAVA技巧 the view, but I would have liked to get a product collection as it is done currently in most categories/views.

Any ideas?


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);

Usage:

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

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


You have to set that category to Anchor = Yes in de backend. That way your collection will nculde all the products form his subcategories.


If you wanted to show all products assigned to a category below the root category of a store you could do the following (or replace root category with the one you desire):

$root_category = Mage::getModel('catalog/category')->load(Mage::app()->getStore()->getRootCategoryId());
$all_cat_ids = explode(",", $root_category->getAllChildren());
$collection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left');
$collection->addAttributeToFilter('category_id', array('in' => $all_cat_ids));

Hope this helps.


Similar to the answer by Matt, but without the "XXX already exists" error.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once 'app/Mage.php';
umask(0);
$app = Mage::app('admin');

$rootCategory = Mage::getModel('catalog/category')->load(17);
$collection = Mage::getResourceModel('catalog/product_collection');
$allCatIds = explode(",", $rootCategory->getAllChildren());
$collection
    ->getSelect()
    ->group('entity_id');
$collection
    ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id=entity_id', null, 'left')
    ->addAttributeToFilter('category_id', array('in' => $allCatIds));

echo $collection->count();


Sorry for the incomplete answer, but an approach that might work is to look at the category path for the parent (1/2/3) and use a query (on a category collection?) that grabs all descendents of that category (path like 1/2/3%). Then, you could use that to filter a product collection. Maybe someone else can flesh out those details and answer better :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜