开发者

How to get a list of categories by product number?

I need to sort categoies by product number that means which category has large number of products is shown at the top of category list. 开发者_运维技巧So catgories list should be descending order by product number. any help would be appreciated!

I have categories and its product as following as:

category                           no of products

cell phones                                 5
cameras                                     8
computers                                   3

I would like to sort categories cameras,cell phones,computers by product number .For this sorting result i would like to use join in collection class of category.


The following code will fetch the product per category:-

$productCollection = Mage::getResourceModel('catalog/product_collection')
                         ->addCategoryFilter($category);

$productCount = $productCollection->count();

You can do in this way:-

  • Get an array of all categories
  • Loop through them
  • Fetch product collection with product count for each category (from the above code).
  • Sort categories with the product count.

Hope this helps. Thanks.


If you have a collection of categories called $collection then you can do this:

$collection->setOrder('children_count', 'desc');

Edit:
To make it the default in an overridden collection use this method:

protected function _initSelect()
{
    parent::_initSelect();
    $this->setOrder('children_count', 'desc');
    return $this;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜