3

I am trying to get the number of orders with status 'processing' and below is the code.

$countProcessingOrders = 0;    

$processingOrders = Mage::getModel('sales/order')->getCollection()
    ->addFilter('status', Mage_Sales_Model_Order::STATE_PROCESSING)
    ->addAttributeToSelect('created_at');

foreach ($processingOrders as $order) {
        $countProcessingOrders++; 
}

For some reason, the (count) output compared to Magento Admin is off by one. It would be helpful if anyone can give clues as to why this may occur?

Note: I am selecting the 'created_at' attribute for some other purpose.

10
  • If you're running this in a one-off script, make sure to set the default timezone first.
    – philwinkle
    Jul 16, 2013 at 13:45
  • 1
    Have a look at the collections getSize() method as compared to count() or manual looping if you don't need the collection items otherwise. It is much more efficient.
    – Vinai
    Jul 16, 2013 at 13:54
  • @philwinkle Atleast for this question, the timezone doesn't matter because I am not using the 'created_at' attribute in this case. I just want to get the count of orders in 'processing' status. Jul 16, 2013 at 13:57
  • @Vinai if I can get the count right first then, I would be happy to optimize the code. Jul 16, 2013 at 13:59
  • 1
    Use Mage::getModel('sales/order')->getCollection()->addFilter('status', Mage_Sales_Model_Order::STATE_PROCESSING)->getSize()
    – Vinai
    Jul 16, 2013 at 14:03

2 Answers 2

2

You can try this way:

$processingOrders = Mage::getModel('sales/order')->getCollection()
    ->addFieldToFilter('state', Mage_Sales_Model_Order::STATE_PROCESSING) //use state instead of status since 'processing' is a state of the order not a status.
    ->addAttributeToSelect('created_at');
$total = $processingOrders->count();
3
  • Sorry, my bad. I've change the answer. I modified addFilter to addFieldToFilter
    – Marius
    Jul 16, 2013 at 13:53
  • Using 'state' instead of 'status' doesn't seem to help. The count is way off compared to the count in Magento Admin. Jul 16, 2013 at 13:53
  • Modifying addFilter to addFieldToFilter has the same result as using 'state' instead of 'status'. Both of these don't return the expected count (the count displayed in Magento Admin being the expected result). Jul 16, 2013 at 13:56
1

Magento admin backend uses sales_flat_order_grid table. Try use this one:

$processingOrders = Mage::getModel('sales/order_grid')->getCollection()
    ->addFieldToFilter('state', Mage_Sales_Model_Order::STATE_PROCESSING)
    ->addAttributeToSelect('created_at');
$total = $processingOrders->count();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.