How to Create a Custom Module and To Add A Column To Existing Database Table In Magento 2

Step1:

Follow these steps to create a module:

  1. Create the module folder.
  2. Create the etc/module.xml file.
  3. Create the registration.php file.
  4. Run the bin/magento setup:upgrade script to install the new module.
  5. Check if the module is working.

Method To Add A Column To Existing Database Table In Magento 2:

Step 1: Create a file called ‘InstallSchema.php’ in the setup folder of the module, i.e.

(app/code/vendor/modulename/Setup/InstallSchema.php)
and make use of following code:
Here I am using code for adding a column in quote section
<?php
namespace Vendor\Extension\Setup;
 use Magento\Framework\Setup\InstallSchemaInterface;
 use Magento\Framework\Setup\ModuleContextInterface;
 use Magento\Framework\Setup\SchemaSetupInterface;
 /**
 @codeCoverageIgnore
 */
 class InstallSchema implements InstallSchemaInterface
 { 
 /**
 {@inheritdoc}
 @SuppressWarnings(PHPMD.ExcessiveMethodLength)
 */
 public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
 {
     $installer = $setup;
     $installer->startSetup();
 $installer->getConnection()->addColumn(     $installer->getTable('quote'),     'length',     [         'type' => 'text',         'nullable' => true,         'comment' => 'length',     ] ); $setup->endSetup();
 }
 } 
Step 2: After saving files, you need to run php bin/magento setup:upgrade. Now check your database and you will be able to find a new custom table and new column. 

Note: If you face any issue, it may be due to the module that you have already installed. As you know, if the module is already installed then setup:upgrade command does not install schema. You will need to look into your setup_module table, delete your module from the table and re-run the php bin/magento setup:upgrade command.

Leave a comment

Your email address will not be published. Required fields are marked *