Skip to content

How I can get products using multiple skus?

In my custom block I loaded the ProductRepository:

namespace PcmagasFirstModuleBlockMyList;

class MyList extends MagentoFrameworkViewElementTemplate
{
    private ProductRepository $productRepository;
   
    public function __construct(
        TemplateContext $context,
        ProductRepository $productRepository,
        array $data = []
    ){
        $this->productRepository=$productRepository;
    }

    public function getRelatedProducts()
    {
        /**
         * @var String[]
         */
        $skus = ['24-MB01','24-MB04','24-UG01'];
        return $this->productRepository->get($skus);
    }
}

But this method seem that does not return any product at my phtml:

<?php
    /**
     * @var $block PcmagasFirstModuleBlockMyList
     */
?>
<?=json_encode($block->getRelatedProducts(),JSON_PRETTY_PRINT&JSON_UNESCAPED_UNICODE);?>

But I get the following error:


TypeError: MagentoCatalogModelProductRepository::getProductFromLocalCache(): Argument #1 ($sku) must be of type string, array given, called in /var/www/html/vendor/magento/module-catalog/Model/ProductRepository.php on line 286 and defined in /var/www/html/vendor/magento/module-catalog/Model/ProductRepository.php:818

...

But If I try to use the following:

        return $this->productRepository->get('24-MB01,24-MB04,24-UG01');

I get:


Exception #0 (MagentoFrameworkExceptionNoSuchEntityException): The product that was requested doesn't exist. Verify the product and try again.

If I try this:

        return $this->productRepository->addFieldToFilter('sku',$skus);

I get the error:

Error: Call to undefined method MagentoCatalogModelProductRepositoryInterceptor::addFieldToFilter() in /PcmagasFirstModuleBlockMyList.php:51

Is there a way to search using multiple skus?