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");

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?


Reference Link

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);

| improve this answer | |
  • $this->action is the object of \Magento\Catalog\Model\ResourceModel\Product\Action? – Shoaib Munir May 24 '19 at 7:05
  • yes bro......... – Rk Rathod May 24 '19 at 7:08
  • Thanks Rk Rathod I will try this. Will let you know when it resolved :) – Shoaib Munir May 24 '19 at 7:12
  • ok buddy....... :) – Rk Rathod May 24 '19 at 7:13
  • It worked perfectly. Thanks :) – Shoaib Munir May 24 '19 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.