InstallSchema Magento 2

The InstallSchema will be run during the module install and its used to cretae DB table structure.

The module install script will run when you run the following command line

php bin/magento setup:upgrade

File : app/code/PHPCodez/First/Setup/InstallSchema .php

<?php
namespace PHPCodez\First\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\ModuleContextInterface;

class InstallSchema implements InstallSchemaInterface
{
 public function upgrade( SchemaSetupInterface $setup, ModuleContextInterface $context ) {
 $installer = $setup;

$installer->startSetup();

if(version_compare($context->getVersion(), '1.1.0', '<')) {
 if (!$installer->tableExists('phpcodez_post')) {
 $table = $installer->getConnection()->newTable(
 $installer->getTable('phpcodez_post')
 )
 ->addColumn(
 'post_id',
 \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
 null,
 [
 'identity' => true,
 'nullable' => false,
 'primary' => true,
 'unsigned' => true,
 ],
 'Post ID'
 )
 ->addColumn(
 'name',
 \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
 255,
 ['nullable => false'],
 'Post Name'
 )
 ->addColumn(
 'created_at',
 \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
 null,
 ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT],
 'Created At'
 )->addColumn(
 'updated_at',
 \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
 null,
 ['nullable' => false, 'default' => \Magento\Framework\DB\Ddl\Table::TIMESTAMP_INIT_UPDATE],
 'Updated At')
 ->setComment('Post Table');
 $installer->getConnection()->createTable($table);

$installer->getConnection()->addIndex(
 $installer->getTable('phpcodez_post'),
 $setup->getIdxName(
 $installer->getTable('phpcodez_post'),
 ['name'],
 \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
 ),
 ['name'],
 \Magento\Framework\DB\Adapter\AdapterInterface::INDEX_TYPE_FULLTEXT
 );
 }
 }

$installer->endSetup();
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *