Monday, November 16, 2015

How to upgrade database schema in magento 2 ?

If you want to add more column into existing table of your module you could do following.
Step 1: Create UpgradeSchema.php under Setup folder. Get Idea from following code.

1:  namespace VendorName\ModuleName\Setup;  
2:  use Magento\Framework\Setup\UpgradeSchemaInterface;  
3:  use Magento\Framework\Setup\ModuleContextInterface;  
4:  use Magento\Framework\Setup\SchemaSetupInterface;  
5:  class UpgradeSchema implements UpgradeSchemaInterface  
6:  {  
7:    public function upgrade(SchemaSetupInterface $setup,  
8:                ModuleContextInterface $context){  
9:      $setup->startSetup();  
10:      if (version_compare($context->getVersion(), '1.0.1') < 0) {  
11:        // Get module table  
12:        $tableName = $setup->getTable('table_name');  
13:        // Check if the table already exists  
14:        if ($setup->getConnection()->isTableExists($tableName) == true) {  
15:          // Declare data  
16:          $columns = [  
17:            'imagename' => [  
18:              'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,  
19:              'nullable' => false,  
20:              'comment' => 'image name',  
21:            ],  
22:          ];  
23:          $connection = $setup->getConnection();  
24:          foreach ($columns as $name => $definition) {  
25:            $connection->addColumn($tableName, $name, $definition);  
26:          }  
27:        }  
28:      }  
29:      $setup->endSetup();  
30:    }  
31:  }  
 
Step 2: Change the setup_version value in module.xml

Step 3: Run php bin/magento setup:upgrade command from CLI.

No comments:

Post a Comment