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 $_items
array. 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()
returns null
the item is added using $_items[] = $item
to the collection without that error being thrown. This means if you are using standard models and resource models, $data
probably 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 is entity_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 $data
array would be array('item_id' => 1, 'foo' => 'bar')
.