Magento 2 - Create product programmatically with different store view values
I think the best answer to this question currently looks like this (using price as example attribute):
/** @var \Magento\Catalog\Model\ProductFactory */
protected $productFactory;
/** @var \Magento\Catalog\Model\ResourceModel\Product */
protected $productResourceModel;
public function __construct(
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Model\ResourceModel\Product $productResourceModel
)
{
$this->productFactory = $productFactory;
$this->productResourceModel = $productResourceModel;
}
private function setStoreViewPrice($productId, $storeId, $price)
{
$product = $this->productFactory->create();
$this->productResourceModel->load($product, $productId);
$product->setStoreId($storeId);
$product->setPrice($price);
$this->productResourceModel->saveAttribute($product, 'price');
}
See also https://magento.stackexchange.com/a/114958/35180
As of today no fix has been released by Magento and there are several others having similar issues. There are also many issues on Github describing the same (or similar) problems.
My only work-around right now is to "reset" the fields that M2 feels the need to update.
$this->objectManager->create('Magento\Catalog\Model\Product')
->load($product->getId())
->setStoreId($storeviewId)
->setStatus($storeStatus)
->setDescription('Store description')
->setName(null) // Use default
->setPrice($price) // Store price
->setTaxClassId(null) // Use default
->setVisibility(null) // Use default
->setCountryOfManufacture(null) // Use default
->save();