In Magento I’m using the following code to get a bestsellers data collection:
Model Function:
public function bestSellers($limit = 12){
$storeId = Mage::app()->getStore()->getId();
$_productCollection = Mage::getResourceModel('reports/product_collection')
->addOrderedQty()
->addAttributeToSelect('id')
->setStoreId($storeId)
->addStoreFilter($storeId)
->setOrder('ordered_qty', 'desc') //best sellers on top
->setPageSize($limit);
Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($_productCollection);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($_productCollection);
return $_productCollection;
}
Block Output:
<?php $products = Mage::getModel('tabs/collections')->bestSellers($limit); ?>
<pre>
<?php print_r($productCollection->getData()); ?>
</pre>
However it returns nothing when the addVisibleInCatalogFilterToCollection line is used in the model function, but if I remove the addVisibleInCatalogFilterToCollection line, then it returns an array of expected bestselling product data (including the ones that shouldn’t be visible in the catalog).
How can I return my array of data with the visibility filter working as it should? Rather than returning nothing. Very confused. Thanks in advance!
Here’s the getSelect:
SELECT SUM(order_items.qty_ordered) AS `ordered_qty`, `order_items`.`name` AS `order_items_name`, `order_items`.`product_id` AS `entity_id`, `e`.`entity_type_id`, `e`.`attribute_set_id`, `e`.`type_id`, `e`.`sku`, `e`.`has_options`, `e`.`required_options`, `e`.`created_at`, `e`.`updated_at`, `cat_index`.`position` AS `cat_index_position` FROM `sales_flat_order_item` AS `order_items`
INNER JOIN `sales_flat_order` AS `order` ON `order`.entity_id = order_items.order_id AND `order`.state <> 'canceled'
LEFT JOIN `catalog_product_entity` AS `e` ON (e.type_id NOT IN ('grouped', 'configurable', 'bundle')) AND e.entity_id = order_items.product_id AND e.entity_type_id = 4
INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id='1' AND cat_index.visibility IN(2, 4) AND cat_index.category_id='2' WHERE (parent_item_id IS NULL) GROUP BY `order_items`.`product_id` HAVING (SUM(order_items.qty_ordered) > 0) ORDER BY `ordered_qty` desc
Here is my Block which i use to obtain bestsellers. It also does simple products that are variants of parental configurable products, to configurable products (works correctly only if one simple products is assigned to max 1 configurable product): http://devblog.fishol.pl/bestselling-products-in-magento/