浏览文章
文章信息
Magento2 添加自定义命令 | Magento2 add custom command
12320
1、创建模块;
2、添加CLI命令注入;
/app/code/Aiweline/PriceManager/etc/di.xml
<?xml version="1.0" ?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Framework\Console\CommandList"> <arguments> <argument name="commands" xsi:type="array"> <item name="check_active_status_command" xsi:type="object">Aiweline\PriceManager\Console\Command\UpdateData</item> </argument> </arguments> </type> </config>3、添加
/app/code/Aiweline/PriceManager/Console/Command/UpdateData.php
<?php namespace Aiweline\PriceManager\Console\Command; use Magento\Catalog\Model\Product; use Magento\Framework\App\ObjectManager; class UpdateData extends \Symfony\Component\Console\Command\Command { /** * {@inheritdoc} */ protected function configure() { $this->setName('weline:price:update') ->setDescription('更新代码,做一些更新库存等小事'); parent::configure(); } /** * {@inheritdoc} */ protected function execute(\Symfony\Component\Console\Input\InputInterface $input, \Symfony\Component\Console\Output\OutputInterface $output) { /**@var Product $productModel*/ $productModel = ObjectManager::getInstance()->get(Product::class); $items = $productModel->getCollection()->joinField('qty', 'cataloginventory_stock_item', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left' )->joinTable('cataloginventory_stock_item', 'product_id=entity_id', array('stock_status' => 'is_in_stock')) ->addAttributeToSelect('stock_status') // ->addFieldToFilter('stock_status', ['eq' => 0])->load()->getItems(); ->addFieldToFilter('qty', ['eq' => 0])->load()->getItems(); $count = count($items); $output->writeln("<info>一共缺货 $count 款。</info>"); $qty=999; /**@var Product $product*/ foreach ($items as $product) { $output->writeln("<info>{$product->getSku()}</info>"); $sql = "UPDATE `cataloginventory_stock_item` SET `qty`={$qty},`is_in_stock`=1 WHERE `product_id`={$product->getId()}"; $product->getCollection()->getConnection()->query($sql); } } }4、更新代码
bin/magento s:d:c
5、测试命令
bin/magento w:p:u
运行结果:
提示:m是我设置的命令别名等同于bin/magento。
完毕!