0

In Magento 2,

How to do a mass deletion of all products attribute values, by attribute_code.

For exemple I want to delete all values for attribute_code = "my_code".

EDIT

I also want to update products attribute values by attribute_code.

I found this :

$productActionObject = $objectManager->create('Magento\Catalog\Model\Product\Action');
$productActionObject->updateAttributes($idArray, array('weight' => 15), 0); 

But my weight values are different between each product ids. I want to update attribute according to an array with product_id as key and weight as value:

$array[1] = 14;
$array[2] = 152;
$array[3] = 58;
...

I can't load every products, because there is a lot of values.

Thansk for your help

asked Nov 23, 2020 at 9:45

1 Answer 1

0

Try This

protected $_productCollectionFactory;
protected $_productRepository;
public function __construct(
 .......................................................
 \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
 \Magento\Catalog\Model\ProductRepository $productRepository,
 .......................................................
) {
 .......................................................
 $this->_productCollectionFactory = $productCollectionFactory;
 $this->_productRepository = $productRepository;
 .......................................................
}
public function execute()
{
 $prdcollection = $this->_productCollectionFactory->create();
 $attributeCode = "Attribute_code";
 $attributeValue = "Attribute_Value"
 foreach ($prdcollection as $prdkey => $prdvalue) {
 $prdData = $this->_productRepository->getById($prdvalue->getId());
 $prdData->setCustomAttribute($attributeCode, $attributeValue);
 //$prdData->setData($attributeCode, $attributeValue);
 $this->_productRepository->save($prdData);
 }
}
answered Nov 23, 2020 at 10:39
2
  • Thanks but it's not a solution for me. I don't want to make a one shot script. But it's an import script run every day with a cronjob. Commented Nov 23, 2020 at 10:43
  • Please check my update answer. and update me. Commented Nov 23, 2020 at 11:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.