You can count the no. of Shipment generated for the specific order by order id in Magento 2.
Using Magento\Sales\Api\ShipmentRepositoryInterface interface you need to use getList() method with SearchCriteriaBuilder Object to add filter by order id.
Using Below code snippet, You can fetch the count of shipment for an order,
<?php namespace Path\To\Class; use Exception; use Psr\Log\LoggerInterface; use Magento\Framework\Api\SearchCriteriaBuilder; use Magento\Sales\Api\ShipmentRepositoryInterface; class ShipmentCount { /** * @var ShipmentRepositoryInterface */ private $shipmentRepository; /** * @var SearchCriteriaBuilder */ protected $searchCriteriaBuilder; /** * @var LoggerInterface */ private $logger; public function __construct( ShipmentRepositoryInterface $shipmentRepository, SearchCriteriaBuilder $searchCriteriaBuilder, LoggerInterface $logger ) { $this->shipmentRepository = $shipmentRepository; $this->searchCriteriaBuilder = $searchCriteriaBuilder; $this->logger = $logger; } /** * Total shipment for an order * * @param int $orderId * * @return int */ public function getCountShipmentForOrder($orderId) { $searchCriteria = $this->searchCriteriaBuilder->addFilter('order_id', $orderId)->create(); try { $shipment = $this->shipmentRepository->getList($searchCriteria); $totalShipment = $shipment->getTotalCount(); } catch (Exception $exception) { $this->logger->critical($exception->getMessage()); $totalShipment = 0; } return $totalShipment; } }
Using above code snippet you can get the shipment count for an order.
$orderId = 1; // shipment id $shipmmentCount = $this->getCountShipmentForOrder($orderId);
Output:
2 (Order with 2 shipments.)