Get Number of Orders per Product

1k views Asked by At

I'm trying to build an array of orders => products that I can use in reporting/updating attributes. The format I'm going for is:

//$orders[<number of orders>] = <array of product ids with this many orders>
$orders = array(
    1 => array(1, 2, 3),
    2 => array(4, 5)
    //etc
);

So far the best I can do is

$productCollection = Mage::getModel('catalog/product')
    ->addAttributeToSelect("sku")
    ->getCollection();

$orders = array();

foreach ($productCollection as $product) {

    $ordered = Mage::getResourceModel('reports/product_collection')
        ->addOrderedQty()
        ->addAttributeToFilter('sku', $product->getSku())
        ->setOrder('ordered_qty', 'desc')
        ->getFirstItem();

    $qtyOrdered = $ordered->getOrderedQty();
    $total = $this->_counter - (int)(!$ordered ? 0 : $qtyOrdered);

    if (!is_array($orders[$total])) {

        $orders[$total] = array();
    }

    $orders[$total][] = $product->getId();
}

But this is obviously using a lot of resources, loading the entire product collection.

I think I can get by just using

$ordered = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty();

But I'm having trouble returning/iterating through the results. How do I extract the information I'm looking for?

2

There are 2 answers

1
ndlinh On

This should be better.

$orderItems = Mage::getResourceModel('sales/order_item_collection');

$result = array();
foreach ($orderItems as $item) {
    $result[$item->getOrderId()][] = $item->getProductId();
}

print_r($result);

NOTE: take care about hidden order item (Ex: simple, configurable product)

0
Steve Robbins On
$ordered = Mage::getResourceModel('reports/product_collection')
    ->addOrderedQty();

foreach($ordered as $order) {
    $qtyOrdered = (int)$order->getOrderedQty();
    if (!is_array($totals[$qtyOrdered])) {
        $totals[$qtyOrdered] = array();
    }
    $totals[$qtyOrdered][] = $order->getEntityId();            
}

Works, but it seems to be returning product Ids that don't exists anymore.