I think you want to update the stock for a product programmaticaly, here is an example console command that I have done recently that you can use.
Also here is the link to how to create a console command
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace W2\MassStockChange\Console\Command;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class MassImport extends Command
{
const NAME_ARGUMENT = "name";
const NAME_OPTION = "option";
private $collectionFactory;
/**
* @var StockRegistryInterface
*/
private $stockRegistry;
private $csvProcessor;
private $directoryList;
private $filesystem;
public function __construct(
CollectionFactory $collectionFactory,
StockRegistryInterface $stockRegistry,
\Magento\Framework\File\Csv $csvProcessor,
\Magento\Framework\App\Filesystem\DirectoryList $directoryList,
\Magento\Framework\Filesystem $filesystem,
string $name = null
)
{
parent::__construct($name);
$this->collectionFactory = $collectionFactory;
$this->stockRegistry = $stockRegistry;
$this->csvProcessor = $csvProcessor;
$this->directoryList = $directoryList;
$this->filesystem = $filesystem;
}
/**
* {@inheritdoc}
*/
protected function execute(
InputInterface $input,
OutputInterface $output
)
{
$csvFilename = $input->getArgument(self::NAME_ARGUMENT);
$fileDirectoryPath = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::MEDIA);
$csvFile = $fileDirectoryPath.'/import/csv/';
$csvFile .= $csvFilename;
$data = $this->csvProcessor->getData($csvFile);
foreach ($data as $row) {
$output->writeln("<comment>.$row[0]. </>");
$stockItem = $this->stockRegistry->getStockItemBySku($row[0]);
$stockItem->setQty($row[1]);
$stockItem->setMinQty($row[2]);
$stockItem->setBackorders($row[3]);
$stockItem->setUseConfigBackorders($row[4]);
$stockItem->setIsInStock($row[5]);
$stockItem->setManageStock($row[6]);
$stockItem->setUseConfigManageStock($row[7]);
$this->stockRegistry->updateStockItemBySku($row[0], $stockItem);
}
$output->writeln("<info>Finished!!! </>");
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this->setName("w2_massstockchange:massimport");
$this->setDescription("Stock Mass Modify");
$this->setDefinition([
new InputArgument(self::NAME_ARGUMENT, InputArgument::OPTIONAL, "Name"),
new InputOption(self::NAME_OPTION, "-a", InputOption::VALUE_NONE, "Option functionality")
]);
parent::configure();
}
}