Magento, Magento 2

How to add new column to existing table using db schema in Magento 2

How to add new column to existing table using db schema in Magento 2

In this tutorial, we will learn about how to add new column to existing table using db schema in Magento 2. In previous version, we used UpgradeSchema.php file for add new column into existing table. But, now in Magento 2.3, we can perform an action using the db_schema.xml file.

Let’s start steps about how to add new column to existing table using db schema in Magento 2 :

You may also like this :

1) First of all, Let’s assume that you have created db_schema.xml file. Now, Modify your existing db_schema.xml file at app/code/RH/Helloworld/etc/ folder and add this below code :


<?xml version="1.0"?>
<!--
/**
 * Created By : Rohan Hapani
 */
-->
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
   <table name="rh_helloworld" resource="default" engine="innodb" comment="RH 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>

Here, In addition added short_description column as new column into rh_helloworld table.

2) Secondly, Before running the upgrade command you need to add your schema to db_whitelist_schema.json file by running the following command :


php bin/magento setup:db-declaration:generate-whitelist --module-name=RH_Helloworld

Now, there is a db_whitelist_schema.json file that will be created in /RH/Helloworld/etc folder.

In last, after generate db_schema_whitelist.json file successfully. You need to execute setup upgrade command :

In conclusion, You can see the new column will be added in the database table. Cheers 🙂

I hope this blog will helpful for easily understand how to add new column to existing table using db schema in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged ,