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 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误