Question

i just try to call save method on collection function like bellow code

    class Index extends \Magento\Framework\App\Action\Action
{

    protected $resultPageFactory;
    private $product;
    /**
     * Constructor
     *
     * @param \Magento\Framework\App\Action\Context  $context
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     */
    public function __construct(
        \Magento\Framework\App\Action\Context $context
        \Magento\Catalog\Model\Product $product,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory
    ) {
        $this->resultPageFactory = $resultPageFactory;
        $this->product=$product;
        parent::__construct($context);
    }

    /**
     * Execute view action
     *
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $collection = $this->product->getCollection();
        var_dump($collection->save());exit;
    }
}

it not show any error just go in infinite loop .... no any error.

My Question is what actually happen it save all product or any error ?

Was it helpful?

Solution

When you get collection with no filter, it will get all you products collection.

And then when you use save(); function it will call this function of file: vendor\magento\framework\Model\ResourceModel\Db\Collection\AbstractCollection.php

public function save()
{
    foreach ($this->getItems() as $item) {
        $item->save();
    }
    return $this;
}

It means it will save all the products one by one.

The problem with this function is, if you have used product flat structure, then in your collection only those attributes will available which are used in product listing. And if you use save on your collection it will only store those attributes which are in flat, all other attributes would save with their default values.
I guess that would be a big problem.

The right way to do this is, use foreach in your collection. Here is pseudocode

foreach($collection as $product){
    //Load product by id
    //Update some attribute
    //then save your product
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top