Skip to main content

Magento 2 - Add or Update the Database


In magento 1, we had sql directory for adding or updating the tables in database. In magento 2, it is changed to Setup folder. The folder contains all the sql changes that need to be pushed to database on the module install. You can find the sample code in the git repo.

First create a module as per the blog post. The files inside the setup folder will typically are as below.
- InstallSchema.php
- InstallData.php
- UpgradeData.php

We can use any custom php file in this folder. Need to explore all of them, and will include in another post.

InstallSchema.php typically should have the below code.
<?php

namespace VendorName\SampleModule\Setup;

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

class InstallSchema implements InstallSchemaInterface {

    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context) {
        // code to create the tables
    }

}

InstallData.php typically should have the below code.
<?php

namespace VendorName\SampleModule\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface {

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context) {
        //code to insert initial data to the database
    }

}

UpgradeData.php typically should have the below code.
<?php

namespace VendorName\SampleModule\Setup;

use Magento\Framework\Setup\UpgradeDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class UpgradeData implements UpgradeDataInterface
{
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        //add upgrade data code as per the versions
    }
}


Comments

Popular posts from this blog

Magento 2 - Create a simple module

In magento 2, the creation of module has changed completely. We will go through how to create a module. Like earlier magento, we do not need to put our module files in different folders for code, theme, skin, etc. All, the codes related to the module should be inside one main folder. You can find the sample code in the git repo .