How to add new columns in exiting table using UpgradeSchema

 Let's Play.

First you create following path like :-

yourmagento_root\mage224\app\code\Mag\MCF\Setup\UpgradeSchema.php


<?php

namespace Mag\MCF\Setup;

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

class UpgradeSchema implements UpgradeSchemaInterface
{

    /**
     * {@inheritdoc}
     */
    public function upgrade(SchemaSetupInterface $setup
ModuleContextInterface $context)
    {
        if (version_compare($context->getVersion(), '2.0.6') < 0) {
            $connection = $setup->getConnection();
            $connection->addColumn(
                $setup->getTable('Mag_MCF'),
                'address',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'nullable' => true,
                    'default' => '',
                    'comment' => 'Address field'
                ]
            );
            $connection->addColumn(
                $setup->getTable('Mag_MCF'),
                'mo_number',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                    'length' => 20,
                    'nullable' => true,
                    'comment' => 'Mobile Number'
                ]
            );
            $connection->addColumn(
                $setup->getTable('Mag_MCF'),
                'gender',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 255,
                    'nullable' => true,
                    'default' => '',
                    'comment' => 'Gender'
                ]
            );
        }
        $connection->endSetup();
    }
}


After you add UpgradeSchema.php file and you want to check filed in database
first your open your etc/module.xml file and setup_version change and save.

Comments