Magento – Magento 2: How to set visibility and status to product using collection

attributescollection;magento2module

I'm creating a cron to pass through all the products and set them visible and active.

This is my execute of the cron who runs well:

public function execute(){
    /**
     * @var $item \Magento\Catalog\Model\Product
     * @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
     */

    $items = $this->productCollection->getItems();

    foreach($items as $item){
        echo  $item->getSku() .'<br>';
        $item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
        $item->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        $item->save();
    }
    echo 'finish';
}

I've got a product with none visibility and status disabled, but when I run the function the product is still with none visibility and status disabled.

What I'm doing wrong?

Best Answer

You should replace the $item->save(); with below code:

$item->getResource()->saveAttribute($item, 'visibility');

$item->getResource()->saveAttribute($item, 'status');
Related Topic