3

Is it possible to filter an Mage_Sales_Model_Order collection by item ids?

I need a collection but there are some items inside that I don't want.

I tried it with:

$canceledItemIds = array(101,102,103);
    $orderModel = Mage::getModel('sales/order')->load($order->getId());
    $orderModel->getCollection()
               ->join(array('item' => 'sales/order_item'), 'main_table.entity_id = item.order_id')
               ->addFieldToFilter('item_id', $canceledItemIds);

But that had no effect.

2

Since the ID's are an array you need an IN statement

$canceledItemIds = array(101,102,103);
    $orderModel = Mage::getModel('sales/order')->load($order->getId());
    $orderModel->getCollection()
               ->join(array('item' => 'sales/order_item'), 'main_table.entity_id = item.order_id')
               ->addFieldToFilter('item_id', array('IN' => $canceledItemIds));

for remove multiple/duplicated row for an order

$orderModel->getSelect()->group('main_table.entity_id')
  • sander please add -group('main_table.entity_id') – Amit Bera Mar 30 '15 at 10:46
  • @AmitBera not sure what you mean. Feel free to edit my answer! :) – Sander Mangel Mar 30 '15 at 10:48
  • 1
    The strange thing is that it sounds good but the result is an collection with all items. It seems that it has no effect to add the filter. But I guess I have another solution: In sales_flat_order_items is a column 'qty_canceled'. This seems easier to filter. But again when I try to filter items with an value of '0' that means all items that are not canceled I get also a collection all items. Maybe I'm to stupid for this. ' – Timo.Klement Mar 30 '15 at 12:34
1

Hi remove load function from ->load($order->getId()); for getting order-collection filter by item id.AS sander say need to use in at collection condition.

Mage::getModel('sales/order')->load($order->getId()) wil give you particular order it object and does not provide all order collection. More about filter see at .

For getting a collection please try with format

Mage::getModel('modelsPrefix/modelname')->getCollection();

thus you can get order collection by

Mage::getModel('sales/colllection')->getCollection();





$canceledItemIds = array(101,102,103)   
 $orderModel = Mage::getModel('sales/order')
$orderModel->getCollection()
               ->join(array('item' => 'sales/order_item'), 'main_table.entity_id = item.order_id')
               ->addFieldToFilter('item_id',array('in', $canceledItemIds));

then remove the duplicate and multiple rows for each order when order have multiple items use group by

$orderModel->getSelect()->group('main_table.entity_id');

Note: item_id give the order item id not product id.Forgetting product id try use field product_id.See at sale_flat_order_item table at db

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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