Search code examples
phpmagentozend-db

Magento Save make insert instead of update


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


Solution

  • 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;