Get Credit memo details by order id programmatically Magento 2.

You can get the Credit memo collection details for the specific order by an order id using Magento 2.

Using Magento\Sales\Api\CreditmemoRepositoryInterface interface, you need to use getList() function to fetch no. of credit memo by sales order id.

Using SearchCriteriaBuilder Class, You need to filter by order id and pass search criteria object to getList() method of CreditmemoRepositoryInterface.

Database Table used the store the credit memo data:
sales_creditmemo

<?php
namespace Path\To\Class;

use Exception;
use Psr\Log\LoggerInterface;
use Magento\Sales\Api\Data\CreditmemoInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Api\CreditmemoRepositoryInterface;

class CreditmemoDetails
{
    /**
     * @var CreditmemoRepositoryInterface
     */
    private $creditmemoRepository;

    /**
     * @var SearchCriteriaBuilder
     */
    protected $searchCriteriaBuilder;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        CreditmemoRepositoryInterface $creditmemoRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        LoggerInterface $logger
    ) {
        $this->creditmemoRepository = $creditmemoRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->logger = $logger;
    }

     /**
     * Get Creditmemo data by Order Id
     *
     * @param int $orderId
     * @return CreditmemoInterface[]|null
     */
    public function getCreditMemoByOrderId(int $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;
    }
}

Call from a template or other class by,

$orderId = 1; // order id
$creditmemos = $this->getCreditMemoByOrderId($orderId);

foreach ($creditmemos as $creditmemo) {
    var_dump($creditmemo);
}

Output:

The array of Credit memo collection for a Specific Order.