Magento, Magento 2

Magento 2.3 : Create a New Table using Declarative Schema

Magento 2.3 Create a New Table using Declarative Schema

In Magento 2.3, There are introduce new features about declarative schema which major role is going to simplify installing and updating the schema process. So, here we will learn about how to create a new table using declarative schema.

In the previous version, we need to create InstallData or InstallSchema script to create a new table or add new data in database 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 create a new table using declarative schema :

You may also like this :

1) First of all, Create a db_schema.xml file at app/code/RH/Helloworld/etc/ folder and add this below code :

<?xml version="1.0" encoding="UTF-8"?>
<!--
/**
 * 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" />
      <constraint xsi:type="primary" referenceId="PRIMARY">
         <column name="id" />
      </constraint>
   </table>
</schema>

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

In Last, db_whitelist_schema.json file that will be created in /RH/Helloworld/etc folder by execute above command & table will create successfully.

Now, run php bin/magento s:up

Cheers 🙂

I hope this blog will helpful for easily understand how to create a new table using declarative schema in Magento 2.3.x. 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 ,