What I'm basically trying to do is sort a product collection by sales so that the most sold product is on top.
Since there doesn't seem to be a standard way to do this in Magento, I first want to get the product ID's of the most sold products by category, like this;
$category = Mage::getModel('catalog/category')->load({category_id});
$reports = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->addCategoryFilter($category)
->addOrderedQty()
->setOrder('ordered_qty', 'desc');
After which I will do some magic with these ID's and create my products JSON.
However, first I'd have to filter the reports per category, but the stock addCategoryFilter()
function doesn't work. If I try to do a ->getSelect()
after applying the category filter, and search for something like 'category', I find nothing. The function addCategoryFilter()
doesn't seem to do anything.
How can I fix this?
getSelect()
work, you should do as follow :$myCollection->count(); echo $mycollection->getSelect()->__toString();
ordered_qty
is available, I see it being returned. With the SQL query I will be able to tweak this further, thanks for the help so far!$reports->count();
to my test code, it suddenly works! If I leave it out, it doesn't. Do you have a clue why? The rest of my code is simply doing$reports->getData()
in a foreach loop.getSelect
on a collection withoutcount
'ing first, then thesetOrder
won't be visible.