Search code examples
magento2magento-2.0magento2.2magento2.4

get list of items from sku magento 2 programatically


I want to fetch items from skus. Can anyone suggest me how to do.

The code I am following - The sku i am getting in the variable $productSkus.

private function fetchProducts(array $orderItems): array
{
    $productIds = [];

    foreach ($orderItems as $orderItem) {
        $productIds[] = $orderItem->getProductId();
        $productSkus[] = $orderItem->getSku();
    }

} Now, i want to get all items from the skus array


Solution

  • I saw your function from class vendor/magento/module-sales-graph-ql/Model/OrderItem/DataProvider.php and in the class have productRepository then this Might be work.

        $productIds = [];
    
        foreach ($orderItems as $orderItem) {
            $productIds[] = $orderItem->getProductId();
            $productSkus[] = $orderItem->getSku();
        }
    
        foreach ($productSkus as $productSku) {
            $product = $this->productRepository->get($productSku);
            $productList[$product->getId()] = $product;
        }