如何从 Magento 2 中的目录规则条件获取列表产品

redmaomail 2024-07-24 18:28 阅读数 73 #Magento

红帽云邮外贸主机

从 Magento 2 中的目录规则条件获取列表产品是帮助您创建和观察所有促销活动的方法。在Magento 2商店中,您可以设置两种类型的促销规则:目录规则和购物车规则,但是我们都引用目录规则。根据您的需要,您可以生成多个目录促销规则并为每个规则应用多种条件。

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

以下是如何通过在目录中创建类来从目录规则条件中获取列表产品的详细指南\Magento\Rule\Model\AbstractModel

<?php
 
namespace Example\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;
}
}


红帽云邮外贸主机

分享到:
版权声明:本站内容源自互联网,如有内容侵犯了你的权益,请联系删除相关内容。
    红帽云邮外贸主机
热门
    红帽云邮外贸主机
    红帽云邮外贸主机