From Magento 2.3, use db_schema.xml to create a new table for the database instead of written InstallSchema PHP class. The new database table creation/updating concept in Magento 2.3 is called declarative schema.
From Magento 2.3 You don’t need to create InstallSchema.php and UpgradeSchema.php
Now you can create a database table using a new way by creating DB schema XML file.
Location for db_schema.xml file,
app/code/{Packagename}/{Modulename}/etc/db_schema.xml
You can create your custom table by below XML code,
<?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="my_custom_table" resource="default" engine="innodb" comment="Custom New Table"> <column xsi:type="int" name="entity_id" padding="10" unsigned="true" nullable="false" identity="true" comment="Entity Id"/> <column xsi:type="varchar" name="fullname" nullable="true" length="50" comment="Full name"/> <column xsi:type="varchar" name="email" nullable="true" length="255" comment="Email"/> <column xsi:type="smallint" name="store_id" padding="5" unsigned="true" nullable="true" identity="false" default="0" comment="Store Id"/> <column xsi:type="timestamp" name="created_at" on_update="false" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/> <column xsi:type="timestamp" name="updated_at" on_update="true" nullable="false" default="CURRENT_TIMESTAMP" comment="Updated At"/> <column xsi:type="smallint" name="is_active" padding="5" unsigned="true" nullable="false" identity="false" default="1" comment="Is Active"/> <column xsi:type="date" name="dob" comment="Date of Birth"/> <column xsi:type="text" name="description" nullable="true" comment="Description"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="entity_id"/> </constraint> </table> </schema>
I have taken many different types of the field for creating the new database table. You can take the only required field to create a database table.
<table>…</table> : “Used for create table in Magento 2.3+”
<column>…</column> : “Used for create different column of the table”
You can set int, text, varchar, timestamp, date, datetime, smallint, float, decimal, double etc.
<constraint>…</constraint> : “Used for set of constraint, Like primary key, foreign key, unique key.”
You can set primary key usig constraint tag
<constraint xsi:type="primary" referenceId="PRIMARY"> <column name="entity_id"/> </constraint>
Where name is your primary key field in the above column tag.
Run Magento 2 Upgrade command to create/update table in Magento 2.3
php bin/magento setup:upgrade
Now you can check a new table will be generated in a database using db_schema.xml file.