How To Create a New Table Using Declarative Schema in Magento 2.3

Hello Folks, we are back with another solution series article - how to create a new table using declarative schema in Magento 2.3. Creating or updating a database table in Magento 2.3 is now known as a declarative schema. Because Magento 2.3 uses db_schema.xml to create a new table in the database rather than InstallSchema PHP class. Additionally, while working with Magento 2.3, no need to create InstallSchema and UpgradeSchema PHP classes.

So, now it is easier to create a new database using a declarative schema means creating a db_Schema XML file. Previously, this process was somehow difficult.

Create a new table using declarative schema

Creating a new Magento 2 database schema is now simpler than installing and updating the schema process. So now lets the steps to create a new table in the Magento database using declarative schema.

Step 1: Create a db_schema.xml file

The very first step is to create a new db_schema.xml file at app/code/Milople/Helloworld/etc/. Then copy-paste the below code there.

<?xml version="1.0" encoding="UTF-8"?>

<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
   <table name="milople_helloworld" resource="default" engine="innodb" comment="Milople Helloworld">
      <column xsi:type="smallint" name="id" padding="7" unsigned="false" nullable="false" identity="true" comment="ID" />
      <column xsi:type="varchar" name="author_name" nullable="false" length="20" comment="Name" />
      <column xsi:type="varchar" name="email" nullable="false" length="20" 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>

Step 2: Add this declarative schema at db_whitelist_schema.json

Now, need to add this declarative schema in the db_whitelist_schema.json file. Run the below command to add the Magento database schema.

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

After that, the db_whitelist_schema.json file will be created at /Milople/Helloworld/etc.

Step 3: Run the command

At last, run the upgrade command in the cmd.

php bin/magento s:up

Once you will run the upgrade command, you will see a new database table will be created in your database.

And you’re done!

Save details and check them in the database. If you come across any errors or need some clarification feel free to drop me a line. Happy to help – Always.