John Watson

Hello! My name is Watson and I'm a freelance developer and consultant. I create profitable web sites for clients of all sizes. Contact me and I'll help you build yours.

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:

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.