我想在不实际加载整个客户模型的情况下更新客户。这是我目前的代码:
$customer = Mage::getModel('customer/customer')->load($customerId, 'entity_id');
$customer->setEmail('test@email.com');
$customer->save();
是否可以在不加载模型的情况下更新模型?
答案 0 :(得分:7)
只要定义了模型的ID,下面的代码就可以正常工作,但它会丢失对象以前的数据。
$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;
}
这显然没有上述负面副作用。