How to Add an Extra Column in Your Existing Magento 2 Table?

How to Add an Extra Column in Your Existing Magento 2 Table?

Posted in : Magento , Magento 2 , How to Topics on Date 11 Dec 2017

While doing Magento 2 programming, sometimes you feel a need to add an extra column to your already existing Magento 2 table. That’s why we have come up with another “How to” blog to help you. In this blog, we will use the UpgradeSchema.php file for adding extra columns in existing Magento 2 tables and this file should be under setup folder of the module. So let’s get started.

Here is an example of adding an extra column named as ‘tok_value’ under the table name ‘sales_order_payment’.

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

(app/code/vendor/modulename/Setup/UpgradeSchema.php)

and make use of following code:

<?php

namespace Vendor\Module\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('sales_order_payment');

// Check if the table already exists

if ($setup->getConnection()->isTableExists($tableName) == true) {

// Declare data

$columns = [

'tok_value' => [

'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,

'nullable' => true,

'comment' => 'Token Value',

],

];

$connection = $setup->getConnection();

foreach ($columns as $name => $definition) {

$connection->addColumn($tableName, $name, $definition);

}

 
}

}

 
$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 in ‘sales_order_payment’ table.

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.

Conclusion:

This How to blog on Magento 2 should get you started on adding an extra column to your already existing Magento 2 table. In a case, if you feel this “how to” is like a heavy lifting for you, then Envision Ecommerce has a team of certified Magento developers who can do this heavy lifting for you. You can contact us at info@envisionecommerce.com to perform this “How to” for you.