John Watson

Hello! My name is Watson and I’m a freelance web developer. I create web sites using the latest tech for clients both huge and small. Rent my brain and I’ll help you build your dream project.

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 on the MySql4 object to false. For example, I created a table that uses customer_entity_id as the primary key:

class MyCompany_MyModule_Model_MySql_Subscription
    extends Mage_Core_Model_MySql4_Abstract {
  public function _construct() {
    // Table resource, primary key
    $this->_init('mymodule/mymodule', 'customer_entity_id');
    // The primary key is not an auto_increment field
    $this->_isPkAutoIncrement = false;

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.