UpgradeSchema Magento 2

The UpgradeSchema will be run during module upgrade and its used to alter the table structure.

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

php bin/magento setup:upgrade

We will need to check the attribute setup_version in module.xml at app/code/PHPCodez/v/etc/ and separate the script by each version.

In this example, we will change the attrubute setup_version to higher level.

File: app/code/PHPCodez/First/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
 <module name="PHPCodez_First" setup_version="0.0.2">
 </module>
</config>

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

<?php
namespace PHPCodez\First\Setup;

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

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

$installer->startSetup();

if(version_compare($context->getVersion(), '0.0.2', '<')) {
 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'
 )
 ->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();
 }
}
Share

Leave a Reply

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