Magento 2 Create a install Schema

When we create a custom module sometime we need to add the table for that module. So in magento 2 we use install Schema. So today we learn how to in Magento 2 Create a install Schema? First we need to create the folder in our module directory name Setup. The folder location will be.

QaisarSatti\HelloWorld\Setup

Now we create our InstallSchema file. The file location will be.

QaisarSatti\HelloWorld\Setup\InstallSchema.php

Below is example code to create a table from install Schema.

<?php

namespace QaisarSatti\HelloWorld\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;

class InstallSchema implements InstallSchemaInterface {

    public function install( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
        $installer = $setup;

        $installer->startSetup();

        $table = $installer->getConnection()->newTable(
            $installer->getTable( 'sample_posts' )
        )->addColumn(
            'post_id',
            Table::TYPE_SMALLINT,
            null,
            [ 'identity' => true, 'nullable' => false, 'primary' => true ],
            'Post ID'
        )->addColumn(
            'title',
            Table::TYPE_TEXT,
            255,
            [ 'nullable' => false ],
            'Post Title'
        )->addColumn(
            'content',
            Table::TYPE_TEXT,
            '2M',
            [ ],
            'Post Content'
        )->setComment(
            'Sample Post Table'
        );

        $installer->getConnection()->createTable( $table );

        $installer->endSetup();
    }
}

Example code is available on Github.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply