I've come across an interesting problem with a Magento store that deals primarily in selling configurable products. I have some code that packages up order information and sends it to an external warehouse who then fulfill the order. With this request, I'm using the increment_id
as the identifier. Periodically, we ask the warehouse if the order has shipped and if they report it has, we retrieve the order in Magento via the increment_id
and complete the order by creating a new shipment against it.
Now, this works fine until an order is edited. Due to Magento's handling of configurable products, editing an order involves cancelling the current order and recreating it anew with the same increment_id
. Subsequently, my interactions based on the increment_id
are now scuppered, since only the first (cancelled) order appears to be retrieved when I do something like this, as the increment_id
is no longer unique:
<?php
$order = Mage::getModel('sales/order')->loadByIncrementId(100000001);
?>
Ordinarily, having a duplicate increment_id
is not possible, so I would have expected Magento to give preference to the 'active' order, but this is not the case.
Now, I found a way to get around this with a collection:
<?php
$orders = Mage::getModel('sales/order')
->getCollection()
->addAttributeToFilter('state', array('neq' => Mage_Sales_Model_Order::STATE_CANCELED))
->addAttributeToFilter('increment_id', 100000001);
foreach ($orders as $order) {
// Do what we need with the order
}
?>
However, I'd be interested to know if there's a way to get just one record back from the collection, negating the need for the foreach
. Can this be done?
Use getFirstItem()
$orders = Mage::getModel('sales/order')
->getCollection()
->addAttributeToFilter('state', array('neq' => Mage_Sales_Model_Order::STATE_CANCELED))
->addAttributeToFilter('increment_id', 100000001)
->getFirstItem();
$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
While the answer from Mukesh will technically work, if you have a large dataset returned by a request, it will potentially times out when loading the entire collection, which is what happens on the very first line of the getFirstItem() function. This is outlined here: Top 3 Reasons to Avoid Magento's getFirstItem()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With