I want to programmatically set special prices on products. The below code works perfectly for 1 store view. But I want to have the special price to be applied to the "All Store Views" scope.
$priceFrom = '2021-10-15';
$priceTo = '2021-10-30';
$updateDatetime = new \DateTime();
$priceFrom = $updateDatetime->modify($priceFrom)->format('Y-m-d H:i:s');
$priceTo = $updateDatetime->modify($priceTo)->format('Y-m-d H:i:s');
$prices[] = $this->specialPriceFactory->create()
->setSku('test-sku')
->setStoreId(4)
->setPrice($data[1])
->setPriceFrom($priceFrom)
->setPriceTo($priceTo);
$result[$row]['result'] = $this->specialPrice->update($prices);
I really don't understand why is setStoreId
is required? when I remove it, I get the following error:
3 exception(s):
Exception #0 (Magento\Framework\Exception\CouldNotSaveException): Could not save Prices.
Exception #1 (Zend_Db_Statement_Exception): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'store_id' cannot be null, query was: INSERT INTO `catalog_product_entity_decimal` (`store_id`,`entity_id`,`value`,`attribute_id`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `value` = VALUES(`value`)
Exception #2 (PDOException): SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'store_id' cannot be null
Best Answer
You have to set default store Id like the below code.
0 is the default store id if we have to set 0 then it's applicable for all