How To Add A Column To Existing Database Table In Magento 2
Magento 2 allows a developer to create, upgrade, or delete a table in the database. Earlier I talked about how to create and upgrade database in Magento 2. However, there were queries regarding the programmatic method to add a column to existing database table in Magento 2.
You can use the below code for the same. For example, adding an order delivery date column to the order table in the database.
While development tasks, whenever you need to add a custom column in the existing database table, bookmark this post for reference.
Method To Add A Column To Existing Database Table In Magento 2:
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 |
<?php namespace Vendor\Extension\Setup; use Magento\Framework\Setup\UpgradeSchemaInterface; use Magento\Framework\Setup\ModuleContextInterface; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\DB\Ddl\Table; class UpgradeSchema implements UpgradeSchemaInterface { public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context) { if (version_compare($context->getVersion(), '1.0.1') < 0) { $connection = $setup->getConnection(); $connection->addColumn( $setup->getTable('sales_order'), 'delivery_date', [ 'type' => Table::TYPE_TEXT, 'length' => 255, 'nullable' => true, 'default' => '', 'comment' => 'Add New Filed' ] ); } } } |
Similarly, you can also change column datatype in a table in Magento 2 using the changeColumn
function.
Use the Comments section below to mention any further doubts.
Feel free to share the solution via social media among the Magento community.
Thanks.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
4 Comments
Hello Sanjay,
I add one gst_no Column in Existing table, whenever i change ‘type’ => Table::TYPE_TEXT to ‘type’ => Table::TYPE_VARCHAR ,It is true .because of gst no is a alphanumerical.
Hello Vikram,
If you set text as type and value in the length then the datatype will become varchar.
Thank You
syntax error, unexpected ‘class’ on line 10
Hello Vivek,
The code is proper and working. There may be a mistake in implementation.
Thank you.