我在 Magento 2.3.5 中编写了用于创建目录规则的代码,保存后我有代码可以自动重新索引它。
/** @var \Magento\CatalogRule\Model\Rule $model */
$ruleRepository = $this->_objectManager->get(
\Magento\CatalogRule\Api\CatalogRuleRepositoryInterface::class
);
$catalogRule = $this->_objectManager->create(\Magento\CatalogRule\Model\Rule::class);
$ruleByBoRefId = $this->getRuleByBoRefId($boRefId);
if (isset($ruleByBoRefId["rule_id"]) && $ruleId = $ruleByBoRefId["rule_id"]) {
$catalogRule = $ruleRepository->get($ruleId);
}
$catalogRule->loadPost($catalogRuleData);
//$catalogRule->save();
$ruleRepository->save($catalogRule);
$this->reindexCatalogRule($catalogRule);
代码重新索引:
public function reindexCatalogRule($catalogRule){
if($catalogRule->isRuleBehaviorChanged()){
$this->_objectManager
->create(\Magento\CatalogRule\Model\Flag::class)
->loadSelf()
->setState(0)
->save();
}
$collection = $this->_indexerCollectionFactory->create()->getAllIds();
foreach ($collection as $id) {
$indexer = $this->_indexerFactory->create()->load($id);
$indexer->getState()
->setStatus(\Magento\Framework\Indexer\StateInterface::STATUS_INVALID)
->save();
$indexer->reindexAll();
}
}
但是在重新索引后,该规则仍然不适用于产品。但是,在我进入管理员并编辑之前保存的目录规则 => 单击保存 => 然后我运行 magento 的 Indexer: reindex 命令后,该规则正常应用。我不明白为什么会这样。请帮助我如何自动将规则应用于产品?谢谢