You can fetch the Credit memo collection details by Order Increment Id using Magento 2.
When you check the sales_creditmemo table, order_id available in sales_creditmemo table so you first fetch the order entity id from the order increment id.
To get credit memo records, you first fetch the order id by order increment id and pass order id as SearchCriteriaBuilder addFilter() method.
Pass search criteria object to getList() method of CreditmemoRepositoryInterface to fetch credit memo details by order increment id.
<?php namespace Path\To\Class; use Exception; use Psr\Log\LoggerInterface; use Magento\Sales\Api\Data\CreditmemoInterface; use Magento\Sales\Api\OrderRepositoryInterface; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Sales\Api\CreditmemoRepositoryInterface; class CreditmemoByIncrementId { /** * @var CreditmemoRepositoryInterface */ private $creditmemoRepository; /** * @var SearchCriteriaBuilder */ protected $searchCriteriaBuilder; /** * @var OrderRepositoryInterface */ private $orderRepository; /** * @var LoggerInterface */ private $logger; public function __construct( CreditmemoRepositoryInterface $creditmemoRepository, SearchCriteriaBuilder $searchCriteriaBuilder, OrderRepositoryInterface $orderRepository, LoggerInterface $logger ) { $this->creditmemoRepository = $creditmemoRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->orderRepository = $orderRepository; $this->logger = $logger; } /** * Get Creditmemo data by Order Id * * @param $incrementId * @return CreditmemoInterface[]|null */ public function getCreditMemoByIncrementId($incrementId) { // first fetch order entity id by increment id $orderId = $this->getOrderIdByIncrementId($incrementId); if ($orderId) { $searchCriteria = $this->searchCriteriaBuilder ->addFilter('order_id', $orderId)->create(); try { $creditmemos = $this->creditmemoRepository->getList($searchCriteria); $creditmemoRecords = $creditmemos->getItems(); } catch (Exception $exception) { $this->logger->critical($exception->getMessage()); $creditmemoRecords = null; } } return $creditmemoRecords; } /** * Get Order entity id by Order Increment Id * @param $incrementId * @return int|null */ public function getOrderIdByIncrementId($incrementId) { $searchCriteria = $this->searchCriteriaBuilder ->addFilter('increment_id', $incrementId)->create(); $order = $this->orderRepository->getList($searchCriteria); $orderId = null; if ($order->getTotalCount()) { foreach ($order->getItems() as $orderData) { $orderId = (int)$orderData->getId(); } } return $orderId; } }
Using the above way you got the output as credit memo records as an array.
Iterate over a loop to credit memo array to fetch no. of different credit memo record for an order.
$orderIncrementId = 000000001; // order increment_id $creditmemos = $this->getCreditMemoByIncrementId($orderIncrementId); foreach ($creditmemos as $creditmemo) { var_dump($creditmemo); }
You got the credit memo object for the output of the above code.