Magento Save insert instead of update

I have strange behavior 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 gives me good information, the states change from 0 to 1 (the value of my constant TRANSFER_STATE_RECEIVED_MIDDLEWARE), and the class fits well for Middleware_Model_Transfer.

However the save is trying to do an insert instead of an update and I 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 fully understand that I have a duplicate key on my transfer_request_id and this is obviously correct, but why Magento is trying to insert when I need to update this data I received. Is it possible to force update if found on a model in Magento?

thank

+3


source to share


2 answers


I share the fix for science, but it only fixes in reverse order:

$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 am expecting INSERTION, but due to the data available for the object, Magento will try to UPDATE by default.



Why is this happening? This is because my object has its primary_key (i.e. sample_id) already set with your custom new_id value. Since primary_key is set by default Magento, let's say you want to UPDATE. So it will try to find a record with sample_id = 'new_id'. But in this operation, this will fail, since such data does not exist in the 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 accomplish this, you need to set _isPkAutoIncrement to false. By default, this value is set to yes, which indicates that an update is required if the primary key is set. by setting this to false, tell Magento that I need an INSERT, not an UPDATE. So put this in your model file.

protected $_isPkAutoIncrement = false;

      

+1


source


Can you give an id as well as data and then try to store it as update data.



$tr = Mage::getModel('Middleware/transfer')->load($transfer['transfer_request_id'], 'transfer_request_id');

$tr->setId(11); // Your entity id

$tr->save();

      

+2


source







All Articles