Database – Tables with Non Auto Increment Primary Key

databasemodeltable

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.

Best Answer

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.

Related Topic