I want to delete all the price rules programmatically. How can I achieve this one?
3 Answers
Take a look at the delete sales rule controller: vendor/magento/module-sales-rule/Controller/Adminhtml/Promo/Quote/Delete.php
. As we can see, we can use \Magento\SalesRule\Model\RuleFactory
to delete the invidual sales rule.
We also can use \Magento\SalesRule\Model\RuleRepository::deleteById($ruleId)
.
For the multi rows, we can use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory
;
/** @var \Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory $collectionFactory */
$om = $this->collectionFactory->create();
foreach ($om->getItems() as $item) {
/** @var \Magento\SalesRule\Model\Rule $item */
$item->delete();
}
At Database level: Just delete rows salesrule
DELETE FROM salesrule;
The other tables will be trigger to update.
Create a test.php in root folder and use below code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
/*---------------------------------------------------------------------------*/
$collectionFactory = $obj->create('Magento\SalesRule\Model\ResourceModel\Rule\Collection');
$collectionFactory->walk('delete');
You can use:
public function getList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria);
To get the rule and you can use public function deleteById($ruleId);
to delete any rule in interface Magento\SalesRule\Api\RuleRepositoryInterface
.
Magento recommends to use interfaces
as good Magento2 coding practice.