Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an order with a given increment id already exists in magento?

Tags:

magento

I am new to Magento.

What's the proper way to check if an order with a given increment id already exists ?

The obvious way:

    $order = Mage::getModel('sales/order')->loadByIncrementId($reservedOrderId);
    if ($order) {
        Mage::log('already have order with id ' . $reservedOrderId);
        return $order;
    }

does not work, because I get a new and empty model instance back.

What's the correct way in magento to see if I have no such model for that id ?

like image 412
Thomas Vander Stichele Avatar asked Dec 01 '22 04:12

Thomas Vander Stichele


2 Answers

The most common approach I've seen in core code just load()s a model and checks if there was a primary key assigned. In your case this would look like the following - note the very slight adjustment to the logical condition ($object->getId() vs. $object):

$order = Mage::getModel('sales/order')->loadByIncrementId($reservedOrderId);
if ($order->getId()) {
    Mage::log('already have order with id ' . $reservedOrderId);
    return $order;
}

It's a simple mistake, but remember that a call to load data on a Magento data model will always return the object instance. It's only if there is a result from the storage backend that the object would be decorated with data and therefore a primary key.

like image 115
benmarks Avatar answered Dec 02 '22 18:12

benmarks


In my experience there are two ways to do this:

if ($order->hasData()) {
    // order already exists
}

or, by using a collection;

$collection = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('increment_id', $reservedOrderId);

if ($collection->count()) {
    // order already exists
}

In your case, probably best to use the first one.

like image 35
Daniel Sloof Avatar answered Dec 02 '22 18:12

Daniel Sloof