从 Magento 2中的目录规则条件获取列表产品是帮助您创建和观察所有促销的方法。在Magento 2商店中,您可以设置两种类型的促销规则:目录规则和购物车规则,但是,我们都将参考目录规则。根据您的需要,您可以生成多个目录提升规则,并为每个规则应用各种条件。
以下是如何通过在中创建类来从目录规则条件获取列表产品的详细指南 \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;
}
}
代码片段是最佳选择,因此您可以轻松地从目录规则条件中获取列表产品。希望这是在您的电子商务商店中运行Magento 2平台时获得更好结果的有用主题。