获取每个产品的订单数量

时间:2013-05-02 18:45:56

标签: magento e-commerce report magento-1.12

我正在尝试构建一个订单数组=>我可以用于报告/更新属性的产品。我想要的格式是:

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

到目前为止,我能做的最好的事情是

$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();
}

但这显然是在使用大量资源,加载整个产品系列。

我想我只能使用

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

但是我在返回/迭代结果时遇到了麻烦。如何提取我正在寻找的信息?

2 个答案:

答案 0 :(得分:0)

这应该更好。

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

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

print_r($result);

注意:请注意隐藏的订单项目(例如:简单,可配置的产品)

答案 1 :(得分:0)

$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();            
}

可以使用,但它似乎正在返回不再存在的产品ID。