是否可以在不加载模型的情况下更新模型?
问题描述:
我想在不实际加载整个客户模型的情况下更新客户.这是我当前的代码:
I would like to update a customer without actually loading the entire customer model. Here is my current code:
$customer = Mage::getModel('customer/customer')->load($customerId, 'entity_id');
$customer->setEmail('test@email.com');
$customer->save();
是否可以在不首先加载模型的情况下进行更新?
Is it possible to update the model without first loading it?
答
只要定义了模型的ID,下面的代码就可以正常工作,但是它将丢失对象先前拥有的数据.
The code bellow should work fine as long as the model's ID is defined, it will however loose the previous data the object had.
$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和值来设置属性值.
UPDATE single attribute
The principle is the fact that you can set an attribute value by specifying the entity_id, attribute_code/attribute_id and the value.
/* 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;
}
这显然没有上述负面影响.
This obviously does not have the aforementioned negative side-effect.