Skip to main content

Create a database table in Magento 2

Updated 1 min readMarkdown
Create a database table in Magento 2

Below are steps I went though to create a new database table in Magento 2 / Adobe Commerce

Create a module

You can add to your existing module or follow this blog to create a module

Create a db schema

<?xml version="1.0"?>
<!-- Database schema -->
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema. xsd">
    <table name="az_codez_followers" resource="default" engine="innodb" comment="Azcodez followers">
        <column xsi:type="int" name="follower_id" padding="19" unsigned="true" nullable="false" identity="true" comment="Follower id"/>
        <column xsi:type="text" name="name" nullable="false" comment="Follower Name"/>
        <column xsi:type="text" name="email" nullable="false" comment="Follower Contact"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="follower_id"/>
        </constraint>
    </table>
</schema>

Generate generate db_schema_whitelist.json

docker-compose run --rm deploy magento-command setup:db-declaration:generate-whitelist

Redeploy

Find your table and see if it worked eg.

Select * From az_codez_followers;

image.png

Shameless Plugs

Credits

Feel free to comment with questions or feedback✌️

Happy coding,

Az 👨🏾‍💻

About the author

  • Software engineer focusing on PHP, JavaScript, HTML, CSS, CI/CD, GitHub, AWS, Azure & Magento Commerce. I enjoy code for good projects, tech, gym, nature, travel, fried chicken, and coffee.

    All my articles are educational only from my experience.

    Feel free to connect.

No comments yet. Be the first to comment.