0

As stated in the title, I want to be able to get Product by only the first 6 digit SKU no

Full SKU No : 1350022021000

First 6 Digit SKU : 135002

I have done the code below to test if able to get the product just from the first 6 digits of SKU but apparently, it is not working as I wanted

<?php
namespace MyModule\Custom\Controller\GoogleTagManager;

use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\ResultFactory;

class GetProductData extends Action
{
    public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
    ) {
        $this->productRepository = $productRepository;
    }

    public function execute()
    {
            
        $sku  = "1350022021000"
        $product = $this->productRepository->get($sku);
        // able to get the Product Details


        $sku  = "135002"
        $product = $this->productRepository->get($sku);
        // not able to get , error as below appear

/// Magento\Framework\Exception\NoSuchEntityException: The product that was 
// requested doesn't exist. Verify the product and try again. in 
// /var/www/html/my_system/vendor/magento/module-catalog/Model/ProductRepository.php:276


    }

}

Any help is kindly appreciated, thank you

1 Answer 1

0

First you need to get product collection and then apply SKU filter matching the first digits.

protected $_productCollectionFactory;
        
public function __construct(    
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
)
{    
    $this->_productCollectionFactory = $productCollectionFactory;        
}

$collection = $this->_productCollectionFactory->create();
$collection->addFieldToFilter('sku', ['like' => $firstSixDigitsOfSku.'%']);
2
  • Thank you, I finally able to get the SKU using this Commented Dec 28, 2021 at 6:50
  • $productcollection = $this->productCollection ->addAttributeToFilter([ ['attribute' => 'sku', 'like' => $sku . '%'] ])->load(); $sku = $productcollection->getData()[0]['sku']; $product = $this->productRepository->get($sku); Commented Dec 28, 2021 at 6:50

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.