是否可以在不加载模型的情况下更新模型?

时间:2013-01-16 19:20:21

标签: magento

我想在不实际加载整个客户模型的情况下更新客户。这是我目前的代码:

$customer = Mage::getModel('customer/customer')->load($customerId, 'entity_id');
$customer->setEmail('test@email.com');
$customer->save();

是否可以在不加载模型的情况下更新模型?

1 个答案:

答案 0 :(得分:7)

只要定义了模型的ID,下面的代码就可以正常工作,但它会丢失对象以前的数据。

INSERT

$customer = Mage::getModel('customer/customer');
$customer->setEmail('test@email.com');
$customer->save();
// will create a customer with an email set to `test@email.com`
// everything else will either be default or null

水合作用更新

$customer = Mage::getModel('customer/customer')->load($customerId, 'entity_id');
// this step is also known as `hydration` because the model is like
// a sponge in the watter, it sucks in the values
$customer->setEmail('test@email.com');
$customer->save();
// will update a customer and only ovewrite its email to `test@email.com`
// everything else will be as it was before the save

没有水合作用的更新

$customer = Mage::getModel('customer/customer');
$customer->setId($customerId);
$customer->setEmail('test@email.com');
$customer->save();
// will replace all of the values present on the initial customer with
// an email set to `test@email.com`and everything else set to be default or null

更新单个属性

原则是您可以通过指定entity_id,attribute_code / attribute_id和值来设置属性值。

/* still looking for a usage snippet */

/* defined in `Mage_Eav_Model_Entity_Abstract` */
protected function _setAttributeValue($object, $valueRow)
{
    $attribute = $this->getAttribute($valueRow['attribute_id']);
    if($attribute) {
        $attributeCode = $attribute->getAttributeCode();
        $object->setData($attributeCode, $valueRow['value']);
        $attribute->getBackend()->setEntityValueId($object, $valueRow['value_id']);
    }

    return $this;
}

这显然没有上述负面副作用。