doutan2111 2015-07-20 09:44
浏览 69
已采纳

Magento Save make insert而不是更新

I have a strange behaviour using Magento ( 1.4, old version I know) when I save a custom Model.

                $tr = Mage::getModel('Middleware/transfer')->load($transfer['transfer_request_id'], 'transfer_request_id');
            var_dump(get_class($tr));
            var_dump($tr->getfkState());
            $tr->setData('fk_state', Middleware_Model_TransferState::TRANSFER_STATE_RECEIVED_MIDDLEWARE);
            var_dump($tr->getfkState());
            $tr->save();

My var_dump are giving me some good informations, the states changes from 0 initially to 1 ( the value of my TRANSFER_STATE_RECEIVED_MIDDLEWARE constant), and the class is well a Middleware_Model_Transfer.

However, the save tries to do an insert instead of an update, and i ve got the error below

PHP Fatal error:  Uncaught exception 'Zend_Db_Statement_Exception' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '11' for key 'PRIMARY'' in magento/lib/Zend/Db/Statement/Pdo.php:234

I totally understand that I have a duplicate key on my transfer_request_id and it is obviously true, but why Magento is trying to insert when I need to update this data I got. Is it possible to force the update if found on a model in Magento?

Thanks

  • 写回答

2条回答 默认 最新

  • doudie2693 2016-01-05 14:06
    关注

    I share a fix for science, but it is correcting only in the opposite way :

    $data = array('sample_id'=>'new_id','custid'=>1,'info'=>'info'); 
    $model = Mage::getModel('interface/data')->setData($data); 
    $model->save();
    

    sample_id is my primary key :

    I expect an INSERTION, but due to the data available to the entity, Magento will try to do an UPDATE by default.

    Why It happens so ? This is because my entity has it's primary_key (ie sample_id) is already set with your custom value new_id. Since the primary_key is set, Magento by default, assume you want to perform an UPDATE. So it will try to find a record with sample_id = 'new_id'. But it will fail in this operation since such data is not existing in database.

    How can you overcome this ? But there is a way to do an INSERT rather than doing an UPDATE if the primary key is set. To perform this, you need to set _isPkAutoIncrement to false. By default,this value is set to yes which indicates that we need an update if primary key is set. setting this value to false tells to Magento that, I need an INSERT and not an UPDATE. So put this in your model file.

    protected $_isPkAutoIncrement = false;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效