0
votes

I have a category structure like that:

Root Cat
  Sub Cat 1
  Sub Cat 2
  Sub Cat 3

and a product collection:

$productCollection = Mage::getResourceModel('catalog/product_collection');

Now I would like to sort the products in the collection by category. Sub Cat 1 products should come first, then Sub Cat 2 products and finally Sub Cat 3 products. If I change the order of the categories, the order of the products in the collection should change, too. How can I achieve that? A simple $productCollection->addAttributeToSort('category'); or $productCollection->setOrder('category') does not work.

Thanks in advance!

1

1 Answers

1
votes

I don't think you can achieve all the functionality you want by simply modifying the collection. category isn't an attribute. category_ids is, but when I tried sorting on it it had no effect.

I would get the categories (in the order you want), then get the products from those categories using the addCategoryFilter() function.

Example:

$categories = Mage::getModel('catalog/category')->getCollection();
foreach ($categories as $category) {
    echo $category->getId() . ':' . PHP_EOL;
    $products = Mage::getModel('catalog/product')->getCollection()
        ->addCategoryFilter($category);
    foreach ($products as $product) {
        // Do something
        echo '  ' . $product->getSku() . PHP_EOL;
    }
}