How to Create table with table field using programmatically

Let's Play

First you create following path like :-

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



<?php
namespace Mag\MCF\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
    ) {
        $setup->startSetup();
        $context->getVersion();

        $table = $setup->getConnection()->newTable(
            $setup->getTable('Mag_MCF')
        )->addColumn(
            'id',
            Table::TYPE_INTEGER,
            null,
            [
                'identity' => true,
                'unsigned' => true,
                'nullable' => false,
                'primary' => true
            ],
            'ID'
        )->addColumn(
            'name',
            Table::TYPE_TEXT,
            255,
            [],
            'Name'
        )->addColumn(
            'firstname',
            Table::TYPE_TEXT,
            255,
            [],
            'FirstName'
        )->addColumn(
            'lastname',
            Table::TYPE_TEXT,
            255,
            [],
            'LastName'
        )->addColumn(
            'created_at',
            Table::TYPE_TIMESTAMP,
            null,
            [
                'nullable' => false,
                'default' => Table::TIMESTAMP_INIT
            ],
            'Created date'
        )->addColumn(
            'updated_at',
            Table::TYPE_TIMESTAMP,
            null,
            [
                'nullable' => false,
                'default' => Table::TIMESTAMP_INIT
            ],
            'Updated date'
        )->addIndex(
            $setup->getIdxName('tablename', ['id']),
            ['id']
        )->setComment(
            'table related comments'
        );
        $setup->getConnection()->createTable($table);
        $setup->endSetup();
    }
}

After you change run this command :-

php bin/magento s:up
php bin/magento s:s:d (if site developer mode write -f)
php bin/magento c:c
php bin/magento c:f

And then open the your database and check :-




NOTE :- InstallSchema.php file run only one time.
> $context->getVersion() returns the respective database value for that
 module from the setup_module table, and that is used in the conditional 
state.

> startSetup() && endSetup()-The startSetup() and endSetup() methods are used in setup scripts. They are often at the beginning and the end of an upgrade/install method, like in “upgrade()” method of Magento/Catalog/Setup/UpgradeData.php And you get more information check thislink .

> getConnection Retrieve connection.

THANKS.

Comments