Site icon Qaisar Satti's Blogs

Magento 2 Create a install Schema

Magento 2 Create a install Schema

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.

Exit mobile version