Magento模型保存方法更新记录而不是插入

时间:2015-09-24 09:09:09

标签: php mysql magento magento-1.9

我有一个图像ID数组,我正在迭代它以将它们插入数据库表'slider_images'。以下是代码段:

        try {
            $sliderImages= Mage::getModel('gallery/sliderImage')->getCollection()
                ->addFieldToFilter('slider_id', array('eq' => $sliderId));

            $sliderImageIds = array_column($sliderImages->getData(), 'gallery_image_id');

            $addImageIds = array_diff($galleryImageIds,$sliderImageIds);
            $deleteImageIds = array_diff($sliderImageIds, $galleryImageIds);

            foreach ($addImageIds as $addImageId) {
                $sliderImageData = array();
                $sliderImageModel = Mage::getModel('gallery/sliderImage');

                $sliderImageData['slider_id'] = $sliderId;
                $sliderImageData['gallery_image_id'] = $addImageId;

                $sliderImageModel->addData($sliderImageData)->save();
            }

            foreach ($deleteImageIds as $deleteImageId) {
                $deleteSliderImageModel = Mage::getModel('gallery/sliderImage');
                $deleteSliderImageModel->setGalleryImageId($deleteImageId)->delete();
            }

            $this->_getSession()->addSuccess(
                $this->__('Total of %d record(s) were successfully updated', count($galleryImageIds))
            );
        }catch (Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }

此处 $ addImageIds 是一个图片ID数组:

Array ( [0] => 1 [2] => 2 )

问题:这里是更新记录,而不是插入新记录。如果我查了一个查询日志

UPDATE `slider_images` SET `gallery_image_id` = '1' WHERE (slider_id='11')

UPDATE `slider_images` SET `gallery_image_id` = '2' WHERE (slider_id='11')

和表架构如下所示

enter image description here

我想插入这些值而不是更新。

任何帮助表示感谢。

2 个答案:

答案 0 :(得分:1)

在循环$sliderImageModel->unsetData();方法之后调用save

<强>更新 改变如下代码:

unset($sliderImages);
foreach ($addImageIds as $addImageId) {
    $sliderImageData = array();
    $sliderImageModel = Mage::getModel('gallery/sliderImage');

    $sliderImageData['slider_id'] = $sliderId;
    $sliderImageData['gallery_image_id'] = $addImageId;

    $sliderImageModel->addData($sliderImageData)->save();
    $sliderImageModel->unsetData();
    unset($sliderImageModel);
}

答案 1 :(得分:0)

放置在资源模型gallery/sliderImage

protected $_isPkAutoIncrement = false;