doulu4316 2012-02-15 17:10
浏览 19
已采纳

Magento 1.6 - 将用户输入的数组保存为模型集合

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'
    )
)
  • 写回答

1条回答 默认 最新

  • douchun1948 2012-03-01 20:46
    关注

    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').

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题