Question

I would like to ask you for piece of information that would help me to resolve my issue. My purpose is to get from the Magento database particular product qty in every order (orders must be in exact definied status). I use batch/script standing apart from Magento but uses Mage:app. I do not know if I should start with models (which seems to be logical approach but slow in the same time) or to work directly on database (which is more difficult).

Thank you for any advice.

Regards,

Was it helpful?

Solution

Querying the database is not that complicated:

   SELECT * 
     FROM sales_flat_order o
LEFT JOIN sales_flat_order_item i ON o.entity_id = i.order_id
    WHERE o.status IN ('pending', 'processing')
      AND i.product_id = <YOUR_PRODUCT_ID> 

total_qty_ordered field in result will represent the ordered quantity.

Getting ordered items quantity through models is not heavy either:

<?php

require_once('app/Mage.php');
umask(0);
Mage::app('default');

$core_resource = Mage::getSingleton('core/resource');
$orders = Mage::getResourceModel('sales/order_collection');
$orders->getSelect()->joinLeft(array('ordered_products' => $core_resource->getTableName('sales/order_item')), 'main_table.entity_id = ordered_products.order_id', array('ordered_products.*'));
$orders->addAttributeToSelect('*')
       ->addFieldToFilter('status', array('in' => array('pending', 'processing')))
       ->addAttributeToFilter('main_table.store_id', Mage::app()->getStore()->getId())
       ->addAttributeToFilter('ordered_products.product_id', array('eq' => '2'));
foreach($orders as $order) {
    echo 'Order #' . $order->getId() . ': ' . $order->getData('total_qty_ordered') . '<br/>';
}

The first approach may be a faster but the second one will be Magneto-Upgrade-Safe. So you decide which approach to use.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top