Magento 2 - All products attributes updated after update from collection
-
02-03-2021 - |
Question
I have got collection in $collecction
from Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
with some certain conditions
I am updating a custom attribute viewed_count
in foreach
loop like this:
foreach($collection as $k=>$_product){
echo $_product->getSku()." ";
$viewCount = $this->getViewedCount($_product->getId());
$_product->getResource()->saveAttribute($_product, "viewed_count");
$_product->setViewedCount($viewCount);
$_product->save();
}
After this it is successfully updating product viewed count in viewed_count
attribute.
But the issue is: After this code is executed, all other attributes got updated and set to some default values. Can anyone tell me what am I doing wrong?
Solution
updateAttributes
of class \Magento\Catalog\Model\ResourceModel\Product\Action
. Method can update multiple products and attribute values, but if you want to update just one product with one attribute value you can do it like this:
$this->action->updateAttributes([$product->getId()], ['attribute_code' => $newValue], $storeId);