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 Attributes in Setup

Sometimes in our module we require to create product or category attributes automatically on module install. Also, we might require to add extra fields to quote, sales order, invoice, creditmemo tables. We will go through how to do that in magento 2. You can find the sample code in the git repo .