Magento 1.8 – Get All Orders for a Customer

customermagento-1.8orders

I want to check if the customer logged in has had at least 1 order over €30 euro. What would be the best way to do this?

Best Answer

Use functions below

/**
 * @param int $customerId
 * @param null|float $grandTotal
 *
 * @return bool
 */
public function isCustomerHasOrders($customerId, $grandTotal = null)
{
    $orderCollection = $this->getCustomerOrderCollection($customerId, $grandTotal);
    return (bool)$orderCollection->getSize();
}

/**
 * @param int  $customerId
 * @param null $grandTotal
 *
 * @return Mage_Sales_Model_Resource_Order_Collection
 */
public function getCustomerOrderCollection($customerId, $grandTotal = null)
{    
    $orderCollection = Mage::getResourceModel('sales/order_collection')
        ->addFieldToSelect('*')
        ->addFieldToFilter('customer_id', $customerId)
        ->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))
        ->setOrder('created_at', 'desc')
    ;
    if ($grandTotal && $grandTotal > 0) {
        $orderCollection->addFieldToFilter('base_grand_total', array ('gteq' => $grandTotal));
    }
    return $orderCollection;
}

You can specify order statuses

->addFieldToFilter('state', array('in' => Mage::getSingleton('sales/order_config')->getVisibleOnFrontStates()))

Usage

$customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
$grandTotal = 30;
if ($this->isCustomerHasOrders($customerId, $grandTotal)) {
    // TODO:
}
Related Topic