Today, we’re going to teach you how to add a new column to an existing table in Magento 2.
In the previous version of Magento, this was done by using a UpgradeSchema.php file. But, in the latest Magento 2.3 version, we can add a new column to an existing table using the db_schema.xml file as shown below.
Also read: How to Drop the Table Using Declarative Schema in Magento 2.3?
Steps to Add a New Column to Existing Table using db schema in Magento 2
Here’s an easy and step-by-step process for adding a new column to an existing table using db_schema.xml file in Magento 2.
Step #1
The first step of the process is to create a db_schema.xml file if you haven’t already in the app/code/MD/Helloworld/etc/ directory and copy the following code into the file.
<?xml version="1.0"?> <!-- /** * Created By: MageDelight Pvt. Ltd */ --> <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="md_helloworld" resource="default" engine="innodb" comment="MD Helloworld"> <column xsi:type="smallint" name="id" padding="6" unsigned="false" nullable="false" identity="true" comment="ID" /> <column xsi:type="varchar" name="author_name" nullable="false" length="25" comment="Name" /> <column xsi:type="varchar" name="email" nullable="false" length="25" comment="Email" /> <column xsi:type="varchar" name="description" nullable="false" length="255" comment="Descrition" /> <column xsi:type="varchar" name="short_description" nullable="false" length="255" comment="Short Description" /> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="id" /> </constraint> </table> </schema>
As you can see, we’ve added a new column short_description in the md_helloworld table.
Step #2
Now, before executing the upgrade command, you’ll have to add the schema to db_whitelist_schema.json file using the following command.
php bin/magento setup:db-declaration:generate-whitelist --module-name=MD_Helloworld
Once you execute the above command, the db_whitelist_schema.json file will be created in the /MD/Helloworld/etc directory.
Step #3
Lastly, you need to run the setup upgrade command given below after the db_schema_whitelist_json file has been successfully generated.
php bin/magento s:up
Now, check the output and you’ll see that a new column will be created in your database table.
Also read: How to Create a Custom Database Table in Magento 2?
Conclusion
So, this is how easy it is to add a new column to an existing database table using db schema in Magento 2.
We hope that you found this tutorial helpful. If you’ve any queries, please share them in the comments below. And if you need our professional assistance with your Magento ecommerce development project, feel free to contact us at any time.