Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving single order in Magento by increment_id after editing an order with configurable products

Tags:

php

magento

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?

like image 568
CVM Avatar asked Apr 28 '11 15:04

CVM


3 Answers

Use getFirstItem()

$orders = Mage::getModel('sales/order')
  ->getCollection()
  ->addAttributeToFilter('state', array('neq' => Mage_Sales_Model_Order::STATE_CANCELED))
  ->addAttributeToFilter('increment_id', 100000001)
  ->getFirstItem();
like image 156
Mukesh Chapagain Avatar answered Oct 06 '22 14:10

Mukesh Chapagain


$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
like image 20
Tobias Schifftner Avatar answered Oct 06 '22 14:10

Tobias Schifftner


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()

like image 1
Jeff Monschke Avatar answered Oct 06 '22 14:10

Jeff Monschke