Get order items collection in Magento 2

In an eCommerce store, in order to maintain the inventory, you might require to get order item collection by item ID in Magento 2. The below-mentioned code can help you get order item collection by item ID in Magento 2.

Why Order Item Collections Matter?

Order item operations drive critical workflows:

  • Partial refunds (restock specific items)
  • Custom fulfillment tracking (per-item status)
  • Advanced analytics (best-selling variants)
  • Inventory sync (update stock for returned items)

Method 1: Get Single Order Item by ID


Step 1: Service Contract Approach (Recommended)

<?php
namespace MageDelight\Training\Block;

use Magento\Framework\View\Element\Template;
use Magento\Sales\Api\OrderItemRepositoryInterface;

class Item extends Template 
{
    protected $orderItemRepository;

    public function __construct(
        Template\Context $context,
        OrderItemRepositoryInterface $orderItemRepository,
        array $data = []
    ) {
        $this->orderItemRepository = $orderItemRepository;
        parent::__construct($context, $data);
    }

    /**
     * @param int $itemId
     * @return \Magento\Sales\Api\Data\OrderItemInterface
     * @throws \Magento\Framework\Exception\NoSuchEntityException
     */
    public function getOrderItemById(int $itemId)
    {
        return $this->orderItemRepository->get($itemId);
    }
}


Step 2: Template Usage with Error Handling

<?php
$itemId = 123; // Dynamic value from URL/request
try {
    $item = $block->getOrderItemById($itemId);
    echo "<strong>Order ID:</strong> " . $item->getOrderId() . "<br>";
    echo "<strong>SKU:</strong> " . $item->getSku() . "<br>";
    echo "<strong>Qty:</strong> " . $item->getQtyOrdered();
} catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
    echo "<div class='error'>Item #$itemId not found</div>";
}
?>

 

Method 2: Advanced Order Item Filtering


A. Filter by Product Type

$collection = $this->_orderItemCollectionFactory->create()
    ->addFieldToFilter('product_type', ['in' => ['simple', 'configurable']]);


B. Filter by Custom Status

$collection->addFieldToFilter('status', [
    'in' => [
        \Magento\Sales\Model\Order\Item::STATUS_PENDING,
        \Magento\Sales\Model\Order\Item::STATUS_SHIPPED
    ]
]);


C. Filter by Date Range

$collection->join(
    ['order' => 'sales_order'],
    'main_table.order_id = order.entity_id',
    ['order.created_at']
)->addFieldToFilter('order.created_at', [
    'from' => '2024-01-01',
    'to' => '2024-03-31'
]);

Key Differences: Order vs Item Collections

Aspect Order Collection Order Item Collection
Scope Entire orders Individual items within orders
Common Use Case Bulk order processing Granular item-level operations
Performance Slower (joins multiple tables) Faster (targeted queries)
Typical Filters Customer ID, payment method SKU, product type, item status

 

Real-World Use Cases


1. Partial Order Cancellations

// Cancel 2 units of item #456
$item = $this->orderItemRepository->get(456);
$item->setQtyCanceled(2)
     ->setStatus(\Magento\Sales\Model\Order\Item::STATUS_CANCELED)
     ->save();


2. Fulfillment Tracking

// Mark item as shipped
$item->setData('fulfillment_status', 'shipped')
     ->setData('tracking_number', 'UPS-789456123')
     ->save();


3. Inventory Sync

// Restock returned items
$qtyReturned = $item->getQtyReturned();
$stockItem = $this->stockRegistry->getStockItemBySku($item->getSku());
$stockItem->setQty($stockItem->getQty() + $qtyReturned);
$this->stockRegistry->updateStockItemBySku($item->getSku(), $stockItem);

We hope we covered everything related to get order item collection by item id in Magento 2. If you need our professional help with Magento Development, feel free to reach out.

Also read: