自动在 Magento 中创建购物车价格规则

2021-12-19 00:00:00 oop php magento model-view-controller

我想创建一个购物车价格规则,当用户在我的 Magento 网站上完成一个流程时,他们可以享受 10% 的订单折扣.

I'd like to create a shopping cart price rule that gives a user 10% off their order when and if they complete a process on my Magento site.

此处有一种方法可以将规则直接插入到数据库中.这有点侵犯我的口味.

There's a method here that inserts the rule directly to the database. That's a bit invasive for my tastes.

我将如何使用 Magento 方法来解决这个问题?

How would I go about this using Magento methods?

推荐答案

作为一般原则,您应该能够完成 Magento 系统本身所做的任何事情,而无需编写一行 SQL.几乎所有的 Magento 数据结构都使用 Magento Model 类.

As a general principle, you should be able to do anything that the Magento system itself does without writing a single line of SQL. Almost all the Magento data structures use Magento Model classes.

在某处运行以下代码以查看销售规则/规则模型的样子.这假设您已经在管理员中创建了一个 ID 为 1 的购物车价格规则

Run the following code somewhere to see what a salesrule/rule model looks like. This assumes you've created a single Shopping Cart Price Rule in the admin with an ID of 1

    $coupon = Mage::getModel('salesrule/rule')->load(1);
    var_dump($coupon->getData());

以转储的数据为指导,我们可以使用以下方法以编程方式创建模型

Using the dumped data as a guide, we can programatically create a model using the following

    $coupon = Mage::getModel('salesrule/rule');
    $coupon->setName('test coupon')
    ->setDescription('this is a description')
    ->setFromDate('2010-05-09')
    ->setCouponCode('CODENAME')
    ->setUsesPerCoupon(1)
    ->setUsesPerCustomer(1)
    ->setCustomerGroupIds(array(1)) //an array of customer grou pids
    ->setIsActive(1)
    //serialized conditions.  the following examples are empty
    ->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
    ->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
    ->setStopRulesProcessing(0)
    ->setIsAdvanced(1)
    ->setProductIds('')
    ->setSortOrder(0)
    ->setSimpleAction('by_percent')
    ->setDiscountAmount(10)
    ->setDiscountQty(null)
    ->setDiscountStep('0')
    ->setSimpleFreeShipping('0')
    ->setApplyToShipping('0')
    ->setIsRss(0)
    ->setWebsiteIds(array(1));      
    $coupon->save();

对于任何好奇的人,以上是使用此处

For anyone that's curious, the above is generated code, using the technique discussed here

相关文章