Database schema upgrade
The following Magento 2 tutorial will help you upgrade script for a new version of your extension by adding new tables and columns to a database.
1. Go to the Setup folder and create a new UpgradeSchema.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
namespace Vendor\ModuleName\Setup; use Magento\Framework\Setup\UpgradeSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; class UpgradeSchema implements UpgradeSchemaInterface { public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context){ $setup->startSetup(); if (version_compare($context->getVersion(), '1.0.1') < 0) { // Get module table $tableName = $setup->getTable('table_name'); // Check if the table already exists if ($setup->getConnection()->isTableExists($tableName) == true) { // Declare data $columns = [ 'imagename' => [ 'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT, 'nullable' => false, 'comment' => 'image name', ], ]; $connection = $setup->getConnection(); foreach ($columns as $name => $definition) { $connection->addColumn($tableName, $name, $definition); } } } $setup->endSetup(); } } |
2. In module.xml change setup_version
3. Open CLI and run the following command:
1 |
php bin/magento setup:upgrade |
Source (