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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?xml version="1.0"?> <!-- /** * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ --> <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="custom_form" resource="default" engine="innodb" comment="creating custom form table"> <column xsi:type="smallint" name="entity_id" padding="6" unsigned="false" nullable="false" identity="true" comment="ID"/> <column xsi:type="varchar" name="name" nullable="false" length="25" comment="Name"/> <column xsi:type="varchar" name="email" nullable="false" length="25" comment="Email"/> <column xsi:type="varchar" name="message" nullable="false" length="255" comment="Message"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="entity_id"/> </constraint> </table> </schema> |
<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 :
1 |
php bin/magento setup:db-declaration:generate-whitelist --module-name=MM_Db |
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:
1 |
php bin/magento setup:upgrade |
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”).