We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
How To Create Custom Table In Magento 2
1. Create db_schema.xml
File
In Magento 2.3 and later, it's recommended to use the db_schema.xml
file to define database tables. If you're using an older version of Magento 2, you can use an InstallSchema.php
script instead.
Step 1: Create db_schema.xml
Create the app/code/Vendor/ModuleName/etc/db_schema.xml
file:
<?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="vendor_modulename_custom_table" resource="default" engine="innodb" comment="Custom Table"> <column xsi:type="int" name="entity_id" nullable="false" identity="true" unsigned="true" primary="true" comment="Entity ID"/> <column xsi:type="varchar" name="name" nullable="false" length="255" comment="Name"/> <column xsi:type="text" name="description" nullable="true" comment="Description"/> <column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="false" comment="Creation Time"/> <column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Update Time"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="entity_id"/> </constraint> </table> </schema>
Step 2: Explanation
<table>
: Defines the table name, storage engine (innodb
), and a comment describing the table.<column>
: Defines each column's data type, name, whether it can be null, and any additional options like default values or comments.<constraint>
: Defines constraints such as primary keys or foreign keys.