simian
simian

Reputation: 126

PHP Magento get customers last order total

I am working outside of magento store root folder (1.4) and I would like to get customers order totals, and date of last order. I have started with this:

$customer = Mage::getModel('customer/customer')->load($entity_id);
         $customerTotals =Mage::getResourceModel('sales/sale_collection')
              ->setCustomerFilter($customer)
              ->load()
              ->getTotals();

         echo $customerTotals->getNumOrders();
         echo money_format('$%i',$customerTotals->getLifetime());

This seems to be giving me totals from the wrong customer... Also, can't quite figure out how to get customers last order day.

any help would be appreciated.

Upvotes: 2

Views: 5001

Answers (1)

Drew Hunter
Drew Hunter

Reputation: 10114

This will work, giving you the total number of order, total sales and most recent order for a given customer.

The code could be shortened a little, but for clarity it is as follows...

$customerId = 2;
$orderCollection = Mage::getModel('sales/order')->getCollection()
    ->addFilter('customer_id', $customerId)
    ->setOrder('created_at', Varien_Data_Collection_Db::SORT_ORDER_DESC)
;
$numberOfOrders = $orderCollection->count();
$newestOrder = $orderCollection->getFirstItem();

$orderCollection->clear()->getSelect()
    ->columns(array('total_sales'=>'SUM(main_table.base_grand_total)'))
    ->group('customer_id')
;
$totalSales = $orderCollection->getFirstItem()
    ->getData('total_sales');

//Some output to confirm...
echo "<p>" . $numberOfOrders . "</p>";
echo "<p>" . Mage::helper('core')->currency($totalSales, true, false) ."</p>";
echo "<p>" . $newestOrder->getData('increment_id') ."</p>";

Upvotes: 4

Related Questions