In this article, you going to see how to get order item collection by item ID in Magento 2 with step by step in detail with example.
If you are looking for this topic to get order item collection then you are at right place.
With the help of creating a block file in module, you can easily get order item collection.
Let’s start the topic of Magento 2 get order items collection
Below is the code snippet which help in getting order item collection.
<?php
namespace Vendorname\Modulename\PathtoBlock;
class Item extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\View\Element\Template $context,
\Magento\Sales\Api\OrderItemRepositoryInterface $orderItemRepository,
array $data = []
) {
$this->orderItemRepository = $orderItemRepository;
parent::__construct($context, $data);
}
/* get order Item collection */
public function getOrderItem($itemIid)
{
$itemCollection = $this->orderItemRepository->get($itemId);
return $itemCollection;
}
}
To get all the item related details use the OrderItemRepositoryInterface
interface in constructor.
To call the template file, call the class of template file inside in the constructer.
This Template class file help in view for all data regarding item collection.
In the above code you can see the class path \Magento\Sales\Api\OrderItemRepositoryInterface
.
Then pass the item ID to this Item Repository.
And then it return item collection.
Then the next step is to call the function in the template file.
$itemId = 10; // order item id
$getItemCollection = $block->getOrderItem($itemId);
echo $getItemCollection->getOrderId();
echo "<pre>";print_r($getItemCollection->debug());
Magento 2 get Order details by Increment Id programmatically
Conclusion:
Finally, we done the point of getting order item collection by item ID in Magento
I hope you like this article and if you have any query, please comment below.