从目录规则条件中获取列表产品

在 Magento2 中,根据目录规则条件来获取列表产品可以帮你创建和监控所有的促销。有两种促销规则:目录规则和购物车规则,这里只涉及目录规则。根据你的需要,可以生成多个目录促销规则并且每一个都可以应用各种条件。

以下是如何从目录规则条件中获取类别产品的具体教程,通过创建一个类 \Magento\Rule\Model\AbstractModel

<?php
 
namespace Mageplaza\HelloWorld\Model;
class Rule extends \Magento\Rule\Model\AbstractModel
{
   protected $_productIds;
/**
* Get array of product ids which are matched by rule
*
* @return array
*/
public function getListProductIdsInRule()
{
     $productCollection = \Magento\Framework\App\ObjectManager::getInstance()->create(
         '\Magento\Catalog\Model\ResourceModel\Product\Collection'
     );
     $productFactory = \Magento\Framework\App\ObjectManager::getInstance()->create(
         '\Magento\Catalog\Model\ProductFactory'
     );
     $this->_productIds = [];
     $this->setCollectedAttributes([]);
     $this->getConditions()->collectValidatedAttributes($productCollection);
     \Magento\Framework\App\ObjectManager::getInstance()->create(
         '\Magento\Framework\Model\ResourceModel\Iterator'
     )->walk(
         $this->_productCollection->getSelect(),
         [[$this, 'callbackValidateProduct']],
         [
             'attributes' => $this->getCollectedAttributes(),
             'product' => $productFactory->create()
         ]
     );
     return $this->_productIds;
}
/**
* Callback function for product matching
*
* @param array $args
* @return void
*/
public function callbackValidateProduct($args)
{
     $product = clone $args['product'];
     $product->setData($args['row']);
     $websites = $this->_getWebsitesMap();
     foreach ($websites as $websiteId => $defaultStoreId) {
         $product->setStoreId($defaultStoreId);
         if ($this->getConditions()->validate($product)) {
             $this->_productIds[] = $product->getId();
         }
     }
}
/**
* Prepare website map
*
* @return array
*/
protected function _getWebsitesMap()
{
     $map = [];
     $websites = \Magento\Framework\App\ObjectManager::getInstance()->create(
         '\Magento\Store\Model\StoreManagerInterface'
     )->getWebsites();
     foreach ($websites as $website) {
         // Continue if website has no store to be able to create catalog rule for website without store
         if ($website->getDefaultStore() === null) {
             continue;
         }
         $map[$website->getId()] = $website->getDefaultStore()->getId();
     }
     return $map;
}
}

本教程翻译自Mageplaza模块开发系列,其他内容请点击下面链接: