Skip to content

Instantly share code, notes, and snippets.

@evgv
Last active February 21, 2017 09:22
Show Gist options
  • Save evgv/f7b5ba9300ee3c95a0813ad1aaf50d07 to your computer and use it in GitHub Desktop.
Save evgv/f7b5ba9300ee3c95a0813ad1aaf50d07 to your computer and use it in GitHub Desktop.
Magento. Database model without an auto_increment primary key

Magento database model without an auto_increment primary key

When you create a model in Magento that reads and writes data $model->load() and $model->save() to a database table, by default, Magento expects the primary key of the table to be an auto_increment field called id.

If you want to use a primary key that is not an auto_increment field then you need to set the _isPkAutoIncrement flag to false.

For example:

class {Vendor}_{Extension}_Model_Resource_{Model} extends Mage_Core_Model_Resource_Db_Abstract 
{
    public function _construct()
    {    
        $this->_init('{model alias}/{table alias}', 'entity_id'); // Table resource, primary key
        $this->_isPkAutoIncrement = false; // The primary key is not an auto_increment field
    }
}

If the flag is true (the default), then the save() method will always do an update when you provide a value for the primary key and an insert otherwise. That’s just what you want when the primary key is an auto_increment. If the flag is false, then Magento checks for the existence of a row with that primary key value first. If it exists, it does an update and if it doesn’t exist then it does an insert.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment