10

I have set-up a table in Magento that has two fields, id and date. The date is simply the set to now but the id is actually a foreign key attached to the order id.

My problem is that Magento does not save these objects, no errors happen but nothing is added to the database.

1 Answer 1

19

The problem here is part of the resource save function magento checks if the primary key is set to auto increment and then removes it from the data being saved if this is the case.

In Mage_Core_Model_Resource_Db_Abstract::save you can see how it deals with $this->_isPkAutoIncrement

/**
 * Not auto increment primary key support
 */
if ($this->_isPkAutoIncrement) {
    $data = $this->_prepareDataForSave($object);
    unset($data[$this->getIdFieldName()]);
    $this->_getWriteAdapter()->update($this->getMainTable(), $data, $condition);
} else {
    $select = $this->_getWriteAdapter()->select()
        ->from($this->getMainTable(), array($this->getIdFieldName()))
        ->where($condition);
    if ($this->_getWriteAdapter()->fetchOne($select) !== false) {
        $data = $this->_prepareDataForSave($object);
        unset($data[$this->getIdFieldName()]);
        if (!empty($data)) {
            $this->_getWriteAdapter()->update($this->getMainTable(), $data, $condition);
        }
    } else {
        $this->_getWriteAdapter()->insert($this->getMainTable(), $this->_prepareDataForSave($object));
    }
}

So to fix my issue I simply have to set $_isPkAutoIncrement on my Model's resource to false and Magento will keep the PK in the data and save it into the table.

3
  • 10/10 would upvote again.
    – benmarks
    Mar 31, 2015 at 10:33
  • @benmarks it still amazes me that I stumble apon these sort of things Mar 31, 2015 at 10:34
  • what a good answer and question +1vote for Q&A
    – Amit Bera
    Mar 31, 2015 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.