Magento2 Enterprise更新智能类别

时间:2017-06-02 02:53:36

标签: php magento magento2

我的任务与智能类别有关。智能类别是根据规则分配产品的类别。

类别规则可以是

  • A类:数量超过1000的产品应归入此类别。
  • B类:根据产品品牌分配产品。

Magento 2 Enterprise在添加后为我们提供规则功能,我们可以实现上述功能。但是,只要任何产品完全填满规则,我们就要更新类别,然后它应该分配给规则相关的类别。

在重新保存类别之前,Magento 2 Enterprise不会自动分配遵循规则的新产品。所以我尝试使用cron重新保存智能类别。它的代码是

class Category
{

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    protected $_categoryCollectionFactory;

    /**
     * @var \Magento\Catalog\Api\CategoryRepositoryInterface
     */
    protected $_repository;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @var \Magento\VisualMerchandiser\Model\Rules
     */
    protected $_modelRulesFactory;

    /**
     * Index constructor. Here we are gettingthe logger for log. categorycollection to get all the categories and category repository to save the smart categories
     * @param \Magento\Framework\App\Action\Context $context
     * @param LoggerInterface $logger
     * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
     * @param \Magento\Catalog\Api\CategoryRepositoryInterface $repository
     * @param RulesFactory $modelRulesFactory
     */
    public function __construct(\Psr\Log\LoggerInterface $logger,
                                \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,
                                \Magento\Catalog\Api\CategoryRepositoryInterface $repository,
                                RulesFactory $modelRulesFactory) {
        $this->_logger = $logger;
        $this->_categoryCollectionFactory = $categoryCollectionFactory;
        $this->_repository = $repository;
        $this->_modelRulesFactory = $modelRulesFactory;
    }

    /**
     * In this function we load all the categories and only save the smart categories so rules for products can apply and assign the new best seller products according to rules
     *
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function execute() {
        try{
            $this->_logger->addDebug('Updating categories');
            $categories = $this->_categoryCollectionFactory->create();
            $categories->addAttributeToSelect('*');
            $rulesModel = $this->_modelRulesFactory->create();
            foreach ($categories as $category) {
                $rule = $rulesModel->loadByCategory($category);
                if ($rule->getId() && $rule->getIsActive()) {
                    $category->setStoreId(0);
                    $rule->setIsActive(1);
                    $this->_repository->save($category);
                }
            }
        }catch (Exception $e){
            $this->_logger->addDebug($e->getMessage());
        }
    }
}

上面的代码非常适合那些使用基于默认属性的规则的规则。例如,如果规则是数量> 1000这里的数量是默认属性,因此这些类别更新得很好。但如果它像Brand ='Nike'那样,那么在执行上面的代码之后,它所分配的产品就变成了0.

你能帮我解释它为什么会这样吗?非常感谢你。

0 个答案:

没有答案