Magento 2 How to add new Table to Database in extension.

I have introduced how to create new a Module for Magento 2 in this post. To continue Mangen to 2 extension tutorial, I will introduce How to add new Table to Database in extension in Magento 2 extension,

I will fast create simple module because I have introduced how to create an extension in Previous post so you can check it again if you still confusing about it.

  1. Create the module folder.
  2. Create the etc/module.xml file.
  3. Create the registration.php file.
  4. Create an InstallData script
  5. Run command line php bin/magento setup:upgrade
  6. Create an UpgradeSchema script

Step 1 : Create module folder . Go to in app/code/ and create module’s folder .

Step 2: create module.xml file. Create file module.xml file in
app/code/Magebay/Hello/etc/ . It is importance because this file is required for the module to exist.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Magebay_Hello" setup_version="2.1.5" active="true">
		 <sequence>
              <module name="Magento_Catalog"/>
          </sequence>
    </module>
</config>

Step 3: create registration.php . Create registration.php file in
app/code/Magebay/Hello/

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magebay_Hello',
    __DIR__
);

Step 4 : Create an InstallData script : Create file app/code/Magebay/Hello/Setup/InstallSchema.php

<?php

namespace Magebay\Hello\Setup;

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

/**
 * Class InstallSchema
 * @package Magebay\Hello\Setup
 */
class InstallSchema implements InstallSchemaInterface
{
    /**
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @throws \Zend_Db_Exception
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;

        $installer->startSetup();
        //Create  TABLE
        $table = $installer->getConnection()
            ->newTable($installer->getTable('magebay_news'))
            ->addColumn(
                'news_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
                'New Id'
            )->addColumn(
                'status',
                \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
                null,
                ['nullable' => false, 'default' => 1],
                'Status'
            )->addColumn(
                'title',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                null,
                ['nullable' => false, 'default' => ''],
                'Title'
            )->addColumn(
                'description',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                null,
                ['nullable' => true, 'default' => ''],
                'Description'
            )
            ->addColumn(
                'position',
                \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
                null,
                ['nullable' => false, 'default' => 0],
                'Position'
            )->addColumn(
                'created_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                ['nullable' => false],
                'Created At'
            );
        $installer->getConnection()->createTable($table);
        $installer->endSetup();
    }
}

Step 5 : Run command line php bin/magento setup:upgrade to install and add table for extension.

Step 6 : Create an UpgradeSchema script
I Will add new table magebay_categories and add new category_id in table mabebay_news so I will create file UpgradeSchema.php in app/code/Magebay/Hello/Setup

<?php 
namespace Magebay\Hello\Setup;

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

/**
 * Class UpgradeSchema
 * @package Magebay\Hello\Setup
 */
class UpgradeSchema implements  UpgradeSchemaInterface
{
    /**
     * @param SchemaSetupInterface $setup
     * @param ModuleContextInterface $context
     * @throws \Zend_Db_Exception
     */
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context){
        $setup->startSetup();
		if (version_compare($context->getVersion(), '2.1.6') < 0) {
			$categories = $setup->getTable('magebay_categories');
			if ($setup->getConnection()->isTableExists($categories) != true) {
				$tableCategories = $setup->getConnection()
					->newTable($categories)
					 ->addColumn(
                'category_id',
                \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                null,
                ['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],
                'Id'
            )
            ->addColumn(
                'status',
                \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
                null,
                ['nullable' => false, 'default' => 1],
                'Status'
            )->addColumn(
                'title',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                null,
                ['nullable' => false, 'default' => ''],
                'Title'
            )->addColumn(
                'description',
                \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                null,
                ['nullable' => true, 'default' => ''],
                'Description'
            )
            ->addColumn(
                'position',
                \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
                null,
                ['nullable' => false, 'default' => 0],
                'Position'
            )->addColumn(
                'created_at',
                \Magento\Framework\DB\Ddl\Table::TYPE_TIMESTAMP,
                null,
                ['nullable' => false],
                'Created At'
            )
			->setComment('Magebay Categories ')
			->setOption('type', 'InnoDB')
			->setOption('charset', 'utf8');
				$setup->getConnection()->createTable($tableCategories);
			}
		}
		if (version_compare($context->getVersion(), '2.1.6') < 0) {
			$table = $setup->getTable('magebay_news');
			if ($setup->getConnection()->isTableExists($table) == true) {
                // Declare data
                $columns = [
                    'category_id' => [
                        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                        ['nullable' => true, 'default' => 0],
                        'comment' => 'Category Id',
                    ],
                ];
                $connection = $setup->getConnection();
                foreach ($columns as $name => $definition) {
                    $connection->addColumn($table, $name, $definition);
                }
            }
		}
        if (version_compare($context->getVersion(), '2.1.7') < 0) {
            $table = $setup->getTable('magebay_news');
            if ($setup->getConnection()->isTableExists($table) == true) {
                // Declare data
                $columns = [
                    'image' => [
                        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                        ['nullable' => true, 'default' => ''],
                        'comment' => 'Images',
                    ],
                ];
                $connection = $setup->getConnection();
                foreach ($columns as $name => $definition) {
                    $connection->addColumn($table, $name, $definition);
                }
            }
        }
        if (version_compare($context->getVersion(), '2.1.8') < 0) {
            $table = $setup->getTable('magebay_news');
            if ($setup->getConnection()->isTableExists($table) == true) {
                // Declare data
                $columns = [
                    'number_vote' => [
                        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                        ['nullable' => true, 'default' => 0],
                        'comment' => 'Vote ',
                    ],
                ];
                $connection = $setup->getConnection();
                foreach ($columns as $name => $definition) {
                    $connection->addColumn($table, $name, $definition);
                }
            }
        }
        $setup->endSetup();
    }
}

Change file app/code/etc/module.xml

setup_version="2.1.6"
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Magebay_Hello" setup_version="2.1.6" active="true">
		 <sequence>
              <module name="Magento_Catalog"/>
          </sequence>
    </module>
</config>

In order to update database for extension , you have to run command line
in/magento setup:upgrade and then You will see magebay_categories  Table was added and category_id filed was add to magebay_news

I have introduced How to add new Table to Database in extension in this post so you can build an extension successfully. You can comment under this post if you have any question and then I will check and reply for you. In the next step , I will introduce how to get, insert, update, delete database . This is basic tutorial about Magento 2 extension so I introduce step by step for you. As you can see updating database is very importance for developer because your client’t is always changed and you have to update version for extension so if you understand clear about it, you will have the good extension and manage it more well.