Magento – Filtering ‘reports/product_collection’ doesn’t seem to work properly anymore

magento-1.7magento-enterprise

I'm trying to add filters to a collection as below.

    $collection = Mage::getResourceModel('reports/product_collection')
        ->addOrderedQty()
        ->addAttributeToSelect('*')            
        //->addAttributeToFilter('status', 1)   // doesn't work here but works in old example in link
        //->addAttributeToFilter('visibility', 3)    // doesn't work here but works in old example in link
        ->setOrder('ordered_qty', 'desc'); //best sellers on top

I got this code from this old source (2008), but it seems to be no longer working as-is. It seems that the reports/product_collection only includes a limited number of fields, which excludes sku among many others.

Additionally, even though it includes status and visibility, filtering those attributes doesn't seem to work. e.g. this doesn't work (that's why I commented them out) and the collection will return zero products even though the products I want have those values.

->addAttributeToFilter('status', 1) or ->addAttributeToFilter('visibility', 3)

how can I have it include more fields?

Best Answer

Try like this, this works in Magento 1.7 CE

    $visibility = array(
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH,
        Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG
    );


    $productCollection = Mage::getResourceModel('reports/product_collection')
                        ->addAttributeToSelect('*')
                        ->addOrderedQty()
                        ->addCategoryFilter($category)
                        ->setVisibility($visibility)                   
                        ->setOrder('ordered_qty', 'desc')
                        ->setPage(0, 4);

The category will be the Mage_Catalog_Model_Category $category object.

Update

If you want to add a category filter

$category = Mage::getModel('catalog/category')->load($category_id);

I have been using this code in Magento 1.7 CE. Have you tried in array format array(1,3)?