How to create a database table in Magento 2?

Before Magento 2.3, required to write php scripts to create a new db schema or change in db schema. I.e. InstallData, InstallSchema etc.

Magento 2.3, introduces Declarative Schema to simplify the Magento installation and upgrade processes.

To create a custom module DB table:

You need to create db_schema.xml file in your module etc folder. In this post the module name is MM_Db.

Add below code into db_schema.xml  file to create, custom db table:

My Module Name: MM_Db
Path: magento_root/app/code/MM/Db/etc/db_schema.xml
Table Name: custom_form

db_schema.xml:

<table> …</table> Use for create and set table name
<column> … </column> Use for create and set column of the table
<constraint> … </constraint>  Use for set constraint as like primary key, foreign key, unique key etc
identity=”true” used for auto increment entity_id

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

Now, there is a db_whitelist_schema.json file that will be created in magento_root/app/code/MM/Db/etc/ folder.

Run upgrade command to create table:

Validate your DB for the custom table(custom_form), it should already be created in the DB with with 4 fields, entity_id,name,email,message.

Here entity_id is auto increment(identity=”true” using this attribute) and primary key(constraint, referenceId=”PRIMARY”).

Leave a Reply

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