How to add a column to an existing table in Magento 2?
The Magento 2.3 version release added the ability to add a new column to an existing table using the db_schema.xml file. This process requires some work with code. Here is a step-by-step guide for adding a new column to an existing table in Magento 2.
Warning: all code snippets in this article are examples. You need to customize them to suit your business needs.
Step 1. Create a db_schema.xml file if you haven't already in the app/code/MD/Helloworld/etc/ directory and paste the following code into that file:
<column xsi:type="int" name="id_column" padding="10" unsigned="true" nullable="false" comment="Entity Id"/>
<column xsi:type="int" name="severity" padding="10" unsigned="true" nullable="false" comment="Severity code"/>
<column xsi:type="varchar" name="title" nullable="false" length="255" comment="Title"/>
<column xsi:type="timestamp" name="time_occurred" padding="10" comment="Time of event"/>
+ <column xsi:type="timestamp" name="date_closed" padding="10" comment="Time of event"/>
<constraint xsi:type="primary" referenceId="PRIMARY">
Step 2. Generate the db_whitelist_schema.json file.
bin/magento setup:db-declaration:generate-whitelist --module-name=declarative_table
Step 3. Run the following install update command:
php bin/magento s:up
That’s it. The column was added to the table.
The method is a bit tricky and requires technical skills. If you want to add new columns easily and without programming skills, then you can use our Extended Product Grid with Editor or Extended Order Grid extension. With these modules, the store management will become much easier, and you will save a significant amount of time. In addition, you can filter products and orders using custom parameters, create multiple grid templates, automatically change product availability based on quantity, and work with Magento Enterprise splitted databases.
Read our How to manage Magento 2 products like a pro blog post to learn how to streamline the product management process to improve your productivity, save efforts and time.