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

Ryr*_*yre 2 magento

我想更新客户而不实际加载整个客户模型.这是我目前的代码:

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

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

Mih*_*ncu 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
Run Code Online (Sandbox Code Playgroud)

更新水合作用

$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
Run Code Online (Sandbox Code Playgroud)

更新没有水合作用

$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
Run Code Online (Sandbox Code Playgroud)

UPDATE单个属性

原则是您可以通过指定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;
}
Run Code Online (Sandbox Code Playgroud)

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

  • 哦,还有另一种方式......我无法通过粗略搜索找到它,但原则是您可以通过指定entity_id,attribute_code/attribute_id,value来设置属性值. (2认同)