我正在使用本教程在Magento中添加新的EAV模型:http://inchoo.net/ecommerce/magento/creating-an-eav-based-models-in-magento/
一切都很好,除了当我执行这部分代码时,我的所有属性都以"store_id = 0"保存:
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
我想知道是否有任何明确的方法可以在保存EAV实体属性时设置商店ID。
谢谢。
只有在添加了商店 ID 0 的值后,才能为特定商店设置值。
下面是一个示例。
//create default values
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
//remember the id of the entity just created
$id = $phonebookUser->getId();
//update the name for store id 1
$phonebookUser = Mage::getModel('inchoo_phonebook/user')
->setStoreId(1)
->load($id); //load the entity for a store id.
$phonebookUser->setFristname('Jack'); //change the name
$phonebookUser->save(); //save
我已经覆盖了资源模型中的函数以使用store_id并且它对我有用,但我建议这不是最好的解决方案。
protected function _saveAttribute($object, $attribute, $value)
{
$table = $attribute->getBackend()->getTable();
if (!isset($this->_attributeValuesToSave[$table])) {
$this->_attributeValuesToSave[$table] = array();
}
$entityIdField = $attribute->getBackend()->getEntityIdField();
$data = array(
'entity_type_id' => $object->getEntityTypeId(),
$entityIdField => $object->getId(),
'attribute_id' => $attribute->getId(),
'store_id' => $object->getStoreId(), //added this
'value' => $this->_prepareValueForSave($value, $attribute)
);
$this->_attributeValuesToSave[$table][] = $data;
return $this;
}
protected function _getLoadAttributesSelect($object, $table)
{
$select = $this->_getReadAdapter()->select()
->from($table, array())
->where($this->getEntityIdField() . ' =?', $object->getId())
->where('store_id in (?)', array($object->getStoreId(), 0)); //added this
return $select;
}
此外,我已将此代码添加到实体模型的构造函数中:
if (Mage::app()->getStore()->isAdmin()) {
$this->setStoreId(Mage::app()->getRequest()->getParam('store', 0));
}
else{
$this->setStoreId(Mage::app()->getStore()->getId());
}
重写资源模型中的 _getDefaultAttributes()
方法,如下所示:
protected function _getDefaultAttributes()
{
$attributes = parent::_getDefaultAttributes();
$attributes[] = "store_id";
return $attributes;
}
如果每个模型的实体只有一个store_id
值,则这应该有效。