I had created an Observer of this event:catalog_product_save_after
I am trying to update other products and loading them on the basis of their id, but it is giving me an error. I am Sharing my code here.
Code:-
$product = $observer->getProduct();
$productId = $observer->getProduct()->getId();
$brand = $product->getBrand();
$model = $product->getModel();
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->addAttributeToFilter('model', $model);
$collection->addAttributeToFilter('brand', $brand);
$collection->addAttributeToFilter('visibility', 4);
$collection->addAttributeToSort('price', 'ASC');
$i = 0;
$prodId = [];
foreach ($collection as $value) {
if($i != 0) {
$prodId[] = $value->getId();
}
$i++;
}
foreach($prodId as $mypro) {
$productRepository = $this->_objectManager->get('Magento\Catalog\Model\Product')->load($mypro);
$productRepository->setData('best_price', 0);
$productRepository->save();
}
What I Tried:- I tried to save one product first without using foreach loop but it also gave the same error. I tried to do it by this as well, but received the same error:-
$i = 0;
foreach ($collection as $value) {
if($i != 0) {
$prodId = $value->getId();
$productRepository = $this->_objectManager->get('Magento\Catalog\Model\Product')->load($prodId);
$productRepository->setData('best_price', 0);
$productRepository->save();
}
$i++;
}
Error:
SQLSTATE[HY000]: General error: 1205 Lock wait timeout exceeded; try restarting transaction, query was: UPDATE
catalog_product_entity
SETattribute_set_id
= ?,type_id
= ?,sku
= ?,has_options
= ?,required_options
= ?,created_at
= ?,updated_at
= ? WHERE (entity_id = '5263')
Expected Result: I wanted to save my custom attribute of other's product when one product is saved.
Please help me. I am trying to fix it from a couple of hours but didn't solve. Please guide me.