I’m implementing a user interface on the backend for adding an arbitrary number of values to a product – just like the price tier interface. I’d like to know how saving data like this is usually done.
Below is some simplified code of my attempt (which throws this error: Item with the same id “1” already exists”):
$myItemCollection = $product->getMyItemCollection();
if(!$myItemCollection) {
$myItemCollection = Mage::getModel('my_module/my_item')->getCollection();
}
foreach($product->getMyData('items') as $data) {
$myItem = Mage::getModel('my_module/my_item')->addData($data);
// Item with the same id "1" already exist on the second iteration
$myItemCollection->addItem($myItem);
}
$myItemCollection
->setDataToAll('product_id', $product->getId())
->save();
$product->getMyData(‘items’) returns something like:
array(
1 => array(
'foo' => 'bar'
),
2 => array(
'bin' => 'baz'
),
3 => array(
'buz' => 'fuz'
)
)
The collection uses the
getId()method on the added item to get the array key for the internal$_itemsarray. Your error Item with the same id “1” already exist on the second iteration means you are setting some value on the new models that is returned as an id value.If
getId()returnsnullthe item is added using$_items[] = $itemto the collection without that error being thrown.This means if you are using standard models and resource models,
$dataprobably doesn’t match the array you posted.The key that is used to return the ID value for a model depends on the type of entity.
If the model uses a EAV based resource model (
Mage_Eav_Model_Entity_Abstract), the key isentity_id, e.g.array('entity_id' => 1, 'foo' => 'bar').If the model uses a flat table based resource model (
Mage_Core_Model_Resource_Db_Abstract), the primary key field is (usually) set in the resource model’s_construct()method, as the second parameter to the_init()call.So if the resource model’s initialization looks like
$this->_init('my_module/my_item', 'item_id')the value to set on the$dataarray would bearray('item_id' => 1, 'foo' => 'bar').