Create New Table using Declarative Schema in Magento 2

Hello Everyone,

In this blog, we will learn about how to Create a New Table using Declarative Schema in Magento 2.

Magento introduced a new feature from version 2.3 that is the Declarative Schema feature. We can create a new database table using the db_schema.xml file.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Create a New Table using Declarative Schema in Magento 2.

STEPS FOR CREATE TABLE USING DECLARATIVE SCHEMA IN MAGENTO 2

Step 1: Create db_schema.xml file

app/code/Vendor/Extension/etc/db_schema.xml

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
<table name="magecurious_custom_table" resource="default" engine="innodb" comment="Magecurious Custom Table">
    <column xsi:type="int" name="id" unsigned="true" nullable="false" identity="true" comment="ID"/>
    <column xsi:type="varchar" name="book_name" comment="BookName" nullable="false"/>
    <column xsi:type="varchar" name="book_description" comment="BookDescription" nullable="false"/>
    <column xsi:type="varchar" name="author_name" comment="Author Name" nullable="false" />
     <column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="CreatedAt"/>
    <column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="UpdatedAt"/>
    <constraint xsi:type="primary" referenceId="PRIMARY">
        <column name="id"/>
    </constraint>
</table>
</schema>

Step 2: Create db_schema_whitelist.json file

This file provides history about all tables, columns. It also tells Magento to safely alter the table.

You can run below command to generate db_schema_whitelist.json file

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

Step 3: Finally run the below commands

$ php bin/magento setup:upgrade

Step 4: Output

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Create tables using DB Schema in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Reply

Your email address will not be published. Required fields are marked *