Magento 更改默认付款方式

Magento Changing Default Payment Method

我有一个函数可以对我们在 Magento 中的数据库运行 SQL 原始查询。该函数所做的是将客户的默认信用卡更改为传递给该函数的值。我的问题是如何使用 Magento 模型重写函数。当前函数有效,但我们不希望它直接与 SQL.

交互

函数如下:

public function setDefaultPayment($value)
{
    $customerId = $this->_getSession()->getCustomer()->getId();
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');

    $read = $write->query("SELECT entity_type_id FROM eav_entity_type WHERE entity_type_code='customer'");
    $row = $read->fetch();
    $entity_type_id = $row['entity_type_id'];

    $read = $write->query("SELECT attribute_id FROM eav_attribute WHERE attribute_code='default_payment' AND entity_type_id = $entity_type_id");
    $row = $read->fetch();
    $attribute_id = $row['attribute_id'];

    $read = $write->query("SELECT * FROM customer_entity_int WHERE entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'");
    if ($row = $read->fetch()) {
        $write->update(
            'customer_entity_int',
            array('value' => $value),
            "entity_type_id='$entity_type_id' AND attribute_id='$attribute_id' AND entity_id='$customerId'"
        );
    } else {
        $write->insert(
            'customer_entity_int',
            array(
                'entity_type_id' => $entity_type_id,
                'attribute_id' => $attribute_id,
                'entity_id' => $customerId,
                'value' => $value
            )
        );
    }
}

如果我没看错你的代码,你想用给定的值更新客户属性 default_payment

为此你需要:

  • 通过 id 加载客户
  • 为客户属性设置新值default_payment
  • 拯救客户
public function setDefaultPayment($value)
{
    $customerId = $this->_getSession()->getCustomer()->getId();
    $write = Mage::getSingleton('core/resource')->getConnection('core_write');

    $customer = Mage::getModel('customer/customer')->load($customerId);
    $oldValue = $customer->getDefaultPayment(); // optional, just for checking
    $customer->setDefaultPayment($value);
    $customer->save();

}