문제

I try to delete product but it returns exception can not delete product and sku my code is here

 $productcollection = $this->collectionFactory->create()->addAttributeToSelect('manufacturer','LG')->load();

        foreach ($productcollection as $product) {
            try {

                $this->productRepository->delete($product);
            } catch (StateException $e) {
            }
        }

how can I solve this error ?

도움이 되었습니까?

해결책 3

$productcollection = $this->collectionFactory->create()->addAttributeToSelect('manufacturer','LG')->load();
foreach ($productcollection as $product) {
    try {
        $productcollection->removeItemByKey($product->getId());
    } catch (StateException $e) {
    }
}
return $productcollection;
      }

Thankful of my friend Sandro who helped me with the solution.

다른 팁

If you try to delete product from frontend then you need to assign area for that.

Add following code to your class.

public function __construct(
    ........
    \Magento\Catalog\Model\ProductRepository $productRepository,
    \Magento\Framework\Registry $registry
) {
    ......
    $this->productRepository = $productRepository;
    $this->registry = $registry;
}

Following code is for deleting product.

$this->registry->register('isSecureArea', true);
// using sku
$this->productRepository->deleteById('Z62676');

// using product id
$product = $this->productRepository->getById(1);
$this->productRepository->delete($product);

Delete All Products Example using object manager :

$objectManager->get('Magento\Framework\Registry')->register('isSecureArea', true);
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collection = $productCollection->create()->addAttributeToSelect('*')->load();
$app_state = $objectManager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');

foreach ($collection as $product){
    try {
        echo 'Deleted '.$product->getName()."<br>";
        $product->delete();

    } catch (Exception $e) {
        echo 'Unable to delete product '.$product->getName()."<br>";
        echo $e->getMessage() . "<br>";
    }   
} 

Do some corrections in the code. Hopefully, it will work for you.

$productcollection = $this->collectionFactory->create()->addAttributeToSelect('manufacturer','LG')->load();
    foreach ($productcollection as $product) {
        try {
            $product->delete();
        } catch (StateException $e) {
        }
    }

This code will gives you result what you want.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 magento.stackexchange
scroll top