Step1:
Follow these steps to create a module:
- Create the module folder.
- Create the
etc/module.xmlfile. - Create the
registration.phpfile. - Run the
bin/magento setup:upgradescript to install the new module. - 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.