Magento 1.7 – Get All Orders and Purchased Products for Each Customer

customermagento-1.7magento-communityordersproducts

In Magento 1.7, I need to get all products that each customer bought. I already know how to obtain them but the problem is that the code returns orders, but not separated by customers. I have the following:

//Start Magento application
    include('app/Mage.php');
    Mage::app();
    //Get all ordered items
    $col = Mage::getModel('sales/order_item')->getCollection();    
    foreach($col as $item)
    {
        echo $item->getOrder()->getCustomerName().' bought '. $item->getProduct()->getSku()."\n";
    }

So, I am obtaining orders and from there I see which is the customer that ordered it. But I wonder if there is some method that allow me to, first, obtain the list of all customers, and then for each customer, obtain all the orders and then all products inside the order.
For obtaining customers I have:

$customers = Mage::getModel('customer/customer')->getCollection();
    foreach($customers as $customer)
    {

And I tried $order = $customer->getOrders(); because in recent.phtml it is used and works fine, but here getOrders() is returning null.

I would like to know if there is a simple way to accomplish my purpose. Any help will be appreciated.

Best Answer

You can use below code snippet to get List of bought products for each customer.

$collection = Mage::getModel("sales/order")->getCollection();
$collection->getSelect()->join(
    'sales_flat_order_item', 
    '`sales_flat_order_item`.order_id=`main_table`.entity_id', 
        array(
              'skus' => new Zend_Db_Expr('group_concat(`sales_flat_order_item`.sku SEPARATOR ", ")')
             )
 )->group('main_table.customer_id');
foreach ($collection as $data){
    echo $data->getCustomerName()." bought " . $data->getSkus()."<br />";
}

It will show result like,

Mark Woodland bought abl001, hde013, abl001, hde013, abl001, hde013
Haven Bangor bought hdd001, hdd002, hdd001, hdd002
Related Topic