如何在购物车价格规则中删除过期的优惠券代码? (DB Table salesrule_coupon)

时间:2018-01-20 14:45:14

标签: php magento magento-1.9

当有人注册时事通讯时,我会使用在特定购物车价格规则中生成唯一优惠券代码的脚本。

我现在想删除该规则中过期的优惠券代码而不是自己的规则。我找到的唯一脚本here正在删除整个规则。

如何使用MAGE ::删除下面脚本生成的过期条目?

define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';

//Initializes Mage
Mage::app('admin');


$todaysdateis = date('Y-m-d', strtotime('+14 days'));
$generator = Mage::getModel('salesrule/coupon_massgenerator');
$data = array
(
'max_probability'   => .25,
'max_attempts'      => 10,
'uses_per_customer' => 1,
'uses_per_coupon'   => 1,
'qty'               => 1, //number of coupons to generate
'length'            => 3, //length of coupon string
'to_date'           => "$todaysdateis", //ending date of generated promo
'prefix'            => $prefix,
'format'          => Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC,
'rule_id'         => $rule_id //the id of the shopping cart rule you will use 
as a template
 );

 $generator->validateData($data);
 $generator->setData($data);
 $generator->generatePool();

我发现的代码将删除规则,而不仅是规则中过期的优惠券如下。如何调整,以便删除规则中包含的各个过期优惠券代码?

<?php 
require_once('app/Mage.php');
Mage::app('default');

$allCoupons = Mage::getModel('salesrule/rule')->getCollection()->load();
$rightNow = strtotime('now');
$today = date("Y-m-d", $rightNow);

foreach ($allCoupons as $aCoupon) {
$couponName = $aCoupon->getName();
$subString = substr($couponName,0,16);
$expiryDate = $aCoupon->getToDate();
$expiryDay = date("Y-m-d", $expiryDate);

if(($subString == "XX") && ($today > $expiryDate)) { 
$aCoupon->delete();
}
}

?>

期待收到你的来信!

1 个答案:

答案 0 :(得分:1)

回答我自己的问题。我找到了一个有效的解决方案。但是有更好的一个/更安全吗?

$rightNow = strtotime('now');
$today = date("Y-m-d", $rightNow);

define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app('admin');


$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$salesrule = Mage::getSingleton('core/resource')->getTableName('salesrule_coupon');

$ruleid = '51';

$query = "SELECT * FROM salesrule_coupon WHERE rule_id ='".$ruleid."'";

$results = $read->fetchAll($query);

if ($results){
foreach($results as $result) {

if ($result['expiration_date'] < $today) {
    $querydel = "DELETE FROM salesrule_coupon WHERE coupon_id ='".$result['coupon_id']."'";

    $writeConnection->query($querydel);
   }
}
}