Adding, modifying or dropping a column in a table, the Magento way

This will be really simple. Just create a new install / upgrade script and write the following code into it:

$this->startSetup();
$this->getConnection()->addColumn($this->getTable('your_table_definition'), 'your column name', "column definition");
//example: $this->getConnection()->addColumn($this->getTable('catalog/product'), 'something', "INT(11) COMMENT 'this will create a column named something in catalog_product_entity table'");

$this->endSetup();

So, as you have already seen it, no more ALTER TABLEs.

The same is the situation with changing columns. Here are a couple of useful function declarations (for addColumn, changeColumn, modifyColumn, dropColumn):

    public function addColumn($tableName, $columnName, $definition, $schemaName = null)
    public function changeColumn($tableName, $oldColumnName, $newColumnName, $definition, $flushData = false, $schemaName = null)
    public function modifyColumn($tableName, $columnName, $definition, $flushData = false, $schemaName = null)
    public function dropColumn($tableName, $columnName, $schemaName = null)

The difference between the changeColumn and modifyColumn is that changeColumn modifies also the name of the column and of course the definition also (it uses ALTER TABLE %s CHANGE COLUMN %s %s %s), while modifyColumn changes only the definition (it uses ALTER TABLE %s MODIFY COLUMN %s %s).

One thought on “Adding, modifying or dropping a column in a table, the Magento way”

  1. I havve been surfing online more than 2 hours today, yyet I never found any interesting article like yours.
    It’s pretty woreth enough for me. In my opinion, if aall site
    owners and bloggers made good content as you did, the web will be much more useful than ever before.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.