We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
- Home
- Blog
- eCommerce Talk
- How To Get Order Item Collection By Item Id In Magento 2?
How To Get Order Item Collection By Item Id In Magento 2?
Magento 2 has a lot more to offer than Magento 1.
If you have an eCommerce site running on Magento 2 platform then knowing how to get item data from your online store is a thing you should know about. This post is going to teach you how to retrieve this.
Item data or product data collection in Magento 2 means showing you the number of items present in your store.
The below code describes how to use item id to get order item collection in Magento 2. Let’s fetch the products in your Magento 2 store.
<?php
declare(strict_types=1);
namespace MageSpark\OrderItem\Block;
use Magento\Framework\View\Element\Template;
use Magento\Sales\Api\Data\OrderItemInterface;
use Magento\Sales\Api\OrderItemRepositoryInterface;
/**
* Class Item
*
* @package MageSpark\OrderItem\Block
*/
class Item extends Template
{
/**
* @var OrderItemRepositoryInterface
*/
protected $orderItemRepository;
/**
* Item constructor.
* @param Template $context
* @param OrderItemRepositoryInterface $orderItemRepository
* @param array $data
*/
public function __construct(
Template $context,
OrderItemRepositoryInterface $orderItemRepository,
array $data = []
) {
$this->orderItemRepository = $orderItemRepository;
parent::__construct($context, $data);
}
/**
* Get order Item collection
*
* @param $itemId
* @return OrderItemInterface
*/
public function getOrderItem($itemId): OrderItemInterface
{
return $this->orderItemRepository->get($itemId);
}
}
At last, use the template file to call the function
/**
* @var $block \MageSpark\OrderItem\Block\Item
*/
$itemId = 120; // Use your desired item id here
$itemCollection = $block->getOrderItem($itemId);
echo $itemCollection->getOrderId();
echo "<pre>"; print_r($itemCollection->debug());
That’s it.
Note: You can replace the $itemId as per your need.
Summary
The method to get order item data from item id can be modified depending on your preference and the amount of products your store contains.
If you’ve got any doubt with you, let us know in the comment section below.