0

In my custom block I loaded the ProductRepository:

namespace \Pcmagas\FirstModule\Block\MyList;

class MyList extends \Magento\Framework\View\Element\Template
{
    private ProductRepository $productRepository;
   
    public function __construct(
        Template\Context $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 Pcmagas\FirstModule\Block\MyList
     */
?>
<?=json_encode($block->getRelatedProducts(),JSON_PRETTY_PRINT&JSON_UNESCAPED_UNICODE);?>

But I get the following error:


TypeError: Magento\Catalog\Model\ProductRepository::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 (Magento\Framework\Exception\NoSuchEntityException): 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 Magento\Catalog\Model\ProductRepository\Interceptor::addFieldToFilter() in /Pcmagas\FirstModule\Block\MyList.php:51

Is there a way to search using multiple skus?

2 Answers 2

1

The get method in the Magento\Catalog\Model\ProductRepository class is used to retrieve a single product.

To retrieve multiple products, you need to use the getList method. The implementation should looks the following:

<?php declare(strict_types=1);
namespace Pcmagas\FirstModule\Block\MyList;

use Magento\Catalog\Model\ProductRepository;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\View\Element\Template;

class MyList extends Template
{
    private ProductRepository $productRepository;

    private SearchCriteriaBuilder $searchCriteriaBuilder;

    public function __construct(
        Template\Context $context,
        ProductRepository $productRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->productRepository = $productRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }

    public function getRelatedProducts()
    {
        $skuList = ['24-MB01','24-MB04','24-UG01'];
        $searchCriteria = $this->searchCriteriaBuilder->addFilter('sku', $skuList, 'in')->create();

        return $this->productRepository->getList($searchCriteria)->getItems();
    }
}

In addition, when declaring namespace, adding a backslash at the beginning is valid (namespace \Pcmagas\FirstModule\Block\MyList), you may have an error with this.

1

There are Multiple Ways to get products using multiple skus in Magento2.

Some Repository Basics

  • To get a Single product from a repository use get

  • To get a list of products from a repository use getList

  • To filter any repository use SearchCriteriaBuilder

  • To add a filter use FilterBuilder

  • To group filters use FilterGroupBuilder

In your case, you can use simple product collection to filter a list of products based on the provided skus.

use \Magento\Catalog\Model\ResourceModel\Product\Collection; 

//Inject in your constructor 

/* @var \Magento\Catalog\Model\ResourceModel\Product\Collection  */
$productResourceCollection

$skus = ['24-MB01','24-MB04','24-UG01'];
$_productCollection = $this->productResourceCollection
                        ->addAttributeToSelect(['sku','status','name']) // you can just use * for all attributes
                        ->addAttributeToFilter('sku',['in' => $skus]) // just use in condition to filter the collection 
                        ->load(); 

return $_productCollection

Or you can replace your code with this to filter the product repository

use \Magento\Framework\Api\SearchCriteriaBuilder;
use \Magento\Framework\Api\FilterBuilder;
use \Magento\Framework\Api\Search\FilterGroupBuilder;

//Inject the classes above in the constructor

/* @var \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder */

/* @var \Magento\Framework\Api\SearchCriteriaBuilder $filterBuilder */

/* @var \Magento\Framework\Api\SearchCriteriaBuilder $filterGroupBuilder */

// add this in your method  
$skus = ['24-MB01','24-MB04','24-UG01'];
$skusFilter = $this->filterBuilder
    ->setField(\Magento\Catalog\Api\Data\ProductInterface::SKU)
    ->setConditionType('in')
    ->setValue($skus)
    ->create();
$filterGroupSkusList = $this->filterGroupBuilder->addFilter($skusFilter)->create();
$this->searchCriteriaBuilder->setFilterGroups([$filterGroupSkusList]);
$this->searchCriteriaBuilder->setPageSize(10);
$searchCriteria = $this->searchCriteriaBuilder->create();

$productsList = $this->productRepository->getList($searchCriteria);

if ($productsList->getTotalCount() > 0)  {
    $_products = $productsList->getItems();
    return $_products;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.