Yolanda
Yolanda

Reputation: 23

How to get the correct total number of orders in Magento

I've noticed that there are several ways to get the total number of orders in Magento, using getSize(), for loop, or count(), however, they provide different results within the same time range. I'd like to know what is the best way to get the correct total number of orders in Magento, and what is the difference between getSize(), for loop and count() when calculating the number of orders. Below is the code I used for testing between getSize() and for loop.

//get order total amount
$OrdersAmount_completed = Mage::getModel('sales/order')->getCollection()
    ->addAttributeToFilter('status',array('eq' => Mage_Sales_Model_Order::STATE_COMPLETE))
    ->addAttributeToFilter('created_at', array(
        'from' => $timefrom,
        'to' => $timeto,))
      // ->getSize()  //this generates a difference result with $num_completed
    ;
foreach ($OrdersAmount_completed as $order_completed)
{
    $num_completed++; 
}

Upvotes: 1

Views: 2043

Answers (2)

Yolanda
Yolanda

Reputation: 23

I've figured this one out. It's caused by time zone difference:

//get Magento time zone
echo "Magento System time:".date("m/d/Y h:i:s a", Mage::getModel('core/date')->timestamp(time()));
//get server time zone 
$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;

I've found the server time is using UTC (Coordinated Universal Time), and for Magento it's using something different.

Upvotes: 0

Mihir Bhende
Mihir Bhende

Reputation: 9045

Ideally get Size will always give you proper count. If you get into details, any getCollection() we refer to collection.php inside model/mysql folder.

Inside magento, collection.php extends Mage_Core_Model_Mysql4_Collection_Abstract which extends Mage_Core_Model_Resource_Db_Collection_Abstract which extends Varien_Data_Collection_Db

In Varien_Data_Collection_Db, we have getSize() function which is :

<?php 
  public function getSize()
{
    if (is_null($this->_totalRecords)) {
        $sql = $this->getSelectCountSql();
        $this->_totalRecords = $this->getConnection()->fetchOne($sql, $this->_bindParams);
    }
    return intval($this->_totalRecords);
}

public function getSelectCountSql()
{
    $this->_renderFilters();

    $countSelect = clone $this->getSelect();
    $countSelect->reset(Zend_Db_Select::ORDER);
    $countSelect->reset(Zend_Db_Select::LIMIT_COUNT);
    $countSelect->reset(Zend_Db_Select::LIMIT_OFFSET);
    $countSelect->reset(Zend_Db_Select::COLUMNS);

    $countSelect->columns('COUNT(*)');

    return $countSelect;
}
?>

We can see, it is getting all the count from database depending upon the query.

getSize() will only fetch the count from database. If we get all collection and execute foreach, it is going to fetch all order objects which can be a huge query and also load on the database bandwidth. It is hence, not advisable to do so. :)

Upvotes: 1

Related Questions