In Magento 2, the database schema is defined using XML files that describe the structure of database tables. To add a new column to an existing table, you can create a new database schema file and run the data migration to apply the changes. In this tutorial, we'll guide you through the process of adding a new column to an existing table in Magento 2.
Create a New Database Schema File
- Inside your custom module, create a new
db_schema.xml
file in theSetup
directory. If theSetup
directory does not exist, create it. - In the
db_schema.xml
file, define the new column to be added to the existing table. For example, if you want to add a column namedcustom_field
to thesales_order
table, thedb_schema.xml
file would look like this:
<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="sales_order" resource="sales" engine="innodb" comment="Sales Order">
<column xsi:type="varchar" name="custom_field" nullable="true" length="255" comment="Custom Field"/>
</table>
</schema>
Run the Command
Now, you can run the command to apply the new column to the existing table. Run the following command from the Magento root directory:
php bin/magento setup:upgrade