Magento – Magento 2 – Update multiple products programmatically

apimagento2magento2.2

I'm trying to update products programmatically but I got only first product from array updated. All of products in array have status "2" (disabled) in DB. I'm using $this->productRepositoryInterface – it's \Magento\Catalog\Api\ProductRepositoryInterface

$productSkus = ['A1', 'A2', 'A3'];

foreach ($productSkus as $sku) {
    $productToSave = $this->productRepositoryInterface->get($sku);
    echo "Product {$productToSave->getId()} is loaded and ready to update".PHP_EOL;
    $productToSave->setStatus(1);
    $this->productRepositoryInterface->save($productToSave);
}

After that code executed – I got only A1 set to "Enabled". Other products keeping be disabled. Echo says it's loading everytime new product to be updated. Magento 2.2.4 EE (CE is also affected)

Best Answer

Try to use this below code :

protected $_productCollectionFactory;
protected $_product;

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

public function yourFunction()
{
    $collection = $this->_productCollectionFactory->create()->getCollection();
    foreach ($collection as $value) {
        $product = $this->_product->load($value->getId());
        $product->setStatus(1);
        $product->save();
    }
}

Remove var and generated folder.

Related Topic