Magento get popular products by total number of orders

Posted by Damodar Bashyal on May 10, 2013

 

Magento product report resource collection allows you to get most popular products based on different options for example total number of product orders.

functions we will use: addOrdersCount, setOrder

Let's load this resource collection first like this:

$storeId = Mage::app()->getStore()->getId();
$products = Mage::getResourceModel('reports/product_collection')
     ->addAttributeToSelect('*')
     ->setStoreId($storeId)
     ->addStoreFilter($storeId)
     ->setPageSize(5);

Now, we can pass our filter on the product collection:

$products->addOrdersCount();
// you can pass date range as well
$from = '2013-01-01';
$to = '2013-01-10';
$products->addOrdersCount($from, $to);
$products->setOrder('orders', 'desc');

Source: app\code\core\Mage\Reports\Model\Resource\Product\Collection.php where addOrdersCount looks like below in magento 1.7.0.2

    /**
     * Add orders count
     *
     * @param string $from
     * @param string $to
     * @return Mage_Reports_Model_Resource_Product_Collection
     */
    public function addOrdersCount($from = '', $to = '')
    {
        $orderItemTableName = $this->getTable('sales/order_item');
        $productFieldName   = sprintf('e.%s', $this->getProductEntityId());

        $this->getSelect()
            ->joinLeft(
                array('order_items' => $orderItemTableName),
                "order_items.product_id = {$productFieldName}",
                array())
            ->columns(array('orders' => 'COUNT(order_items2.item_id)'))
            ->group($productFieldName);

        $dateFilter = array('order_items2.item_id = order_items.item_id');
        if ($from != '' && $to != '') {
            $dateFilter[] = $this->_prepareBetweenSql('order_items2.created_at', $from, $to);
        }

        $this->getSelect()
            ->joinLeft(
                array('order_items2' => $orderItemTableName),
                implode(' AND ', $dateFilter),
                array()
            );

        return $this;
    }

And, setOrder looks like this:

 /**
     * Set order
     *
     * @param string $attribute
     * @param string $dir
     * @return Mage_Reports_Model_Resource_Product_Collection
     */
    public function setOrder($attribute, $dir = self::SORT_ORDER_DESC)
    {
        if (in_array($attribute, array('carts', 'orders','ordered_qty'))) {
            $this->getSelect()->order($attribute . ' ' . $dir);
        } else {
            parent::setOrder($attribute, $dir);
        }
 
        return $this;
    }
 
not published on website


QR Code: Magento get popular products by total number of orders