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:
<?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' ] ); } } }
That’s it.
Similarly, you can also change column datatype in a table in Magento 2 using the changeColumn
function.
Feel free to share the solution via social media among the Magento community.
Thanks.