How to Create Custom Table in Magento2 Module?

  • author-img Nidhi Arora
  • 7 years
How to Create Custom Table in Magento2 Module?

Today, we will continue with our ‘How to’ blog series on Magento 2 and help you to create a custom MySQL table in Magento2 module. Let’s do it!

To create a custom table in Magento 2, you need to use InstallSchema.php. However, to add an extra column in Magento 2 tables, you should use UpgradeSchema.php.

Note: In Magento 2, MySQL file should inside the Setup folder under the module.

Here is the code for custom table (called custom_table) creation:

First off, create a file named as InstallSchema.php in the setup folder of module i.e.

(app/code/vendor/modulename/Setup/installschema.php)

and use this code:

<?php

namespace vendor\modulename\Setup;

use Magento\Framework\DB\Ddl\Table as Table;

use Magento\Framework\Setup\InstallSchemaInterface;

use Magento\Framework\Setup\ModuleContextInterface;

use Magento\Framework\Setup\SchemaSetupInterface;

/**

* Class InstallSchema

* @package Eecom\Reservation\Setup

*/

class InstallSchema implements InstallSchemaInterface

{

public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)

{

$setup->startSetup();

/**

* insert new table

*/

$installer = $setup;

/**

* Create table 'custom_table'

*/

$table = $installer->getConnection()->newTable($installer->getTable('custom_table'))

->addColumn(

'id',

Table::TYPE_INTEGER,

null,

['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' => true],

'ID'

)

->addColumn(

'customer_id',

Table::TYPE_INTEGER,

null,

['unsigned' => true, 'nullable' => false],

'Customer ID'

)

->addColumn(

'customer_email',

Table::TYPE_TEXT,

255,

[],

'Customer Email'

)

->setComment('Custom  Table');

 
$installer->getConnection()->createTable($table);

 
$setup->endSetup();

}

}

However, you can change the table name according to your own needs and can also add more columns.

Hope this Magento 2 How to is useful for you and we will see you again in our next “How to” blog on Magento 2. If you have any suggestion or issue don’t hesitate to contact us our certified Magento developers.

Download Blog

ENQUIRY

Ready to Get Started

Communication is the key for us to understand each other. Allow us to understand
your requirements or queries. Present us with an opportunity to serve you.

Fill out the form and out team will get back to you
within 24 hours

    Head Office

    815 Brazos St STE 500, Austin,
    TX 78701, USA