0

I want to get all the products that are sold also with counter like if product1 with 3 (times soled ).I am trying code like this one :

$itemsCollection= Mage::getResourceModel('sales/order_item_collection')
    ->join('order', 'order_id=entity_id');

But How can i get the product counter with that ? My Grid Class method code :

protected function _prepareCollection()
  {
    $itemsCollection = Mage::getResourceModel($this->_getCollectionClass());
    $itemsCollection= Mage::getResourceModel('sales/order_item_collection')
    ->join('order', 'order_id=entity_id');

$itemsCollection->addExpressionFieldToSelect("total_sold" , 'SUM({{qty_ordered}} - {{qty_canceled}})',array("qty_ordered" => "qty_ordered",
                "qty_canceled" => "qty_canceled"));

$itemsCollection = $itemsCollection->getSelect()->group("product_id");
      $this->setCollection($itemsCollection);
      return parent::_prepareCollection();
  }

Now i got Unrecognized method 'setPageSize()' Error.

1 Answer 1

1

Untested by here we go

// Your code
$itemsCollection= Mage::getResourceModel('sales/order_item_collection')
    ->join('order', 'order_id=entity_id');

// sum qty ordered - the canceled qty as it's not really sold if it's canceled. 
// refunded also is debatable
$itemsCollection->addExpressionFieldToSelect("total_sold" , 'SUM({{qty_ordered}} - {{qty_canceled}})',array("qty_ordered" => "qty_ordered",
                "qty_canceled" => "qty_canceled"));

$itemsCollection->getSelect()->group("product_id"); // make sure we group

You will then be able to loop thought the collection and get the total qty per product

foreach($itemsCollection as $item){
            $totalSold = $item->getTotalSold();
        }
6
  • Thanks for your message.I tried your query but i got this error .SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '{qty_ordered - qty_canceled}}) AS total_sold` FROM sales_flat_order_item AS ' at line 1 . Commented Aug 20, 2014 at 5:26
  • Sorry typo. Have corrected Commented Aug 20, 2014 at 5:33
  • Thanks its works but i got another issue on Grid page using above query Unrecognized method 'setPageSize()' .What i am missing ? I have add my new code in question. Commented Aug 20, 2014 at 6:06
  • Are you setting the $collection = $collection->getSelect()->group("product_id"); in your prepareCollection method Commented Aug 20, 2014 at 6:20
  • Yes you can see my code on question.I already put updated code there. Commented Aug 20, 2014 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.