How To Create Database Table Via Module

Module setup script

[ModuleRoot]/sql/[namespace]_[moduleName]_setup/install-0.1.0.php

$installer = $this;
$installer->startSetup();

$connection = $installer->getConnection();
$connection->beginTransaction();

try {

  $table  = $connection->newTable($installer->getTable('database_books/books'))
                       ->addColumn('database_actor_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
                         'unsigned'  => true,
                         'nullable'  => false,
                         'primary'   => true,
                         'identity' => true,
                       ), 'ID actor')
                       ->addColumn('title', Varien_Db_Ddl_Table::TYPE_VARCHAR, null, array(
                         'unsigned'  => true,
                         'nullable'  => false,
                         'primary'   => false,
                       ), 'Firstname')
                       ->addColumn('isbn', Varien_Db_Ddl_Table::TYPE_VARCHAR, null, array(
                         'unsigned'  => true,
                         'nullable'  => false,
                         'primary'   => false,
                       ), 'Lastname');

  $connection->createTable($table);

  $connection->commit(); // Execute SQL,

}catch(Exception $e) {
  Mage::log($e->getMessage());
  $connection->rollBack(); // In case of some error, php revert changes
}

 

Module’s config.php

Our new table has to be declared.

<global>
   <models>
            <pfay_films>
                <class>Pfay_Films_Model</class>
                <resourceModel>pfay_films_resource</resourceModel>
            </pfay_films>
            <pfay_films_resource>
                <class>Pfay_Films_Model_Resource</class>
                <entities>
                    <actors>
                        <table>pfay_actors</table>
                    </actors>
                </entities>
            </pfay_films_resource>
        </models>
</global>

Model

To run our script we need to create model as well.

Once we’re done, we can access data like this

$installer->getTable('pfay_films/actors')

 


Lukas
Lukas Stranovsky
I am the guy who made this. Sorry for typos.