Magento2 : How to database schema upgrade
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.
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();
}
}
Step 2: Change the setup_version
value in module.xml
Step 3: Run php bin/magento setup:upgrade
command from CLI
To upgrade Installer Schema you have to write 'UpgradeSchema.php',
example of UpgradeSchema.php:
namespace <namespace>\<modulename>\Setup;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UpgradeSchemaInterface;
/**
* @codeCoverageIgnore
*/
class UpgradeSchema implements UpgradeSchemaInterface
{
/**
* {@inheritdoc}
*/
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$installer->startSetup();
/*your code here*/
$installer->endSetup();
}
}
Step 2: In your module you will find module.xml inside etc folder in that file change setup_version value(ex: 1.0.1 to 1.0.2) version value should be higher then current version value.
Step 3: Run php bin/magento setup:upgrade command from CLI