I am trying to emulate the same behavior as when you use the admin panel to disable a product. I am trying to do something like this:

$product = $this->productRepository->get($sku);
$product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
$this->productRepository->save($product);

But I still see it as enabled in the admin panel.

Thanks.

有帮助吗?

解决方案

The problem was that $product = $this->productRepository->get($sku); gets a product for the default store. And if you want to disable it globally you need to pass

$this->productRepository->get(
    $sku,
    true/* edit mode */,
    0/* global store*/,
    true/* force reload*/
);

其他提示

You can try with below code,

You can check core file code, vendor/magento/module-catalog-sample-data/Model/Product.php

class Product
{
    public function __construct(
        \Magento\Catalog\Model\ProductFactory $productFactory
    ) {
        $this->productFactory = $productFactory;
    }
    public function saveproduct()
    {

        $product = $this->productFactory->create();
        $product->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
        $product->save();
    }
}
许可以下: CC-BY-SA归因
scroll top