top of page

Insert data while upgrading module (UpgradeData) – setup script – Magento 2

Updated: Aug 21, 2020

This is a continuation of the previous tutorial, It helps to insert data into the database while upgrading the module in Magento 2.

As per our previous tutorials, we summarize the below points

  1. InstallSchema.php script executed while running “bin/magento setup:upgrade” , we use this features to create table structure

  2. Create CRUD object using Model, ResourceModel and Collection for CRUD(Create Read Update Delete) operation

  3. Use above-created CRUD object to insert data into our custom table, InstallData.php script also executed while run “bin/magento setup:upgrade” , we use this features to insert data into our custom table.

  4. UpgradeSchema.php script also executed while run “bin/magento setup:upgrade” and it additionally check version. We use this features to add a column into our existing custom table.

Now we insert data into the database while upgrading the module

When we use UpgradeData

Consider already you launch your module-version-1.0.0 into public marketplace, If you want to add more data into your upcoming version-1.0.1, then you should add logic in UpgradeData.

First change the module version in app/code/Bilal/Cruddemo/etc/module.xml

<?xml version="1.0" ?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
	<module name="Bilal_Cruddemo" setup_version="1.0.1"/>
</config>

Create UpgradeData Script

<?php
namespace Bilal\Cruddemo\Setup;

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

class UpgradeData implements UpgradeDataInterface
{
    private $_cruddemoFactory;

    public function __construct(\Bilal\Cruddemo\Model\CruddemoFactory $cruddemoFactory)
    {
        $this->_cruddemoFactory = $cruddemoFactory;
    }

    public function upgrade( ModuleDataSetupInterface $setup, ModuleContextInterface $context ) {
        if (version_compare($context->getVersion(), '1.0.0') < 0) {
            $data = [
                'name' => 'Vignesh',
                'age' => '26',
                'designation' => 'software programer'
            ];

            $this->_cruddemoFactory->create()->setData($data)->save();
        }
    }
}

If you keenly observe the UpgradeSchema script, you can find the logic of version comparison.

if (version_compare($context->getVersion(), '1.0.1') < 0) {
...........................................................

As we discussed UpgradeSchema.php execute while running setup:upgrade so run the below command in your Magento root

php bin/magento setup:upgrade

If you check your table, you can found our new data.


Recent Posts

See All

Comments


Follow Me

  • LinkedIn
  • Twitter
  • Facebook
  • YouTube
  • Instagram

©2021 by Bilal Usean. Proudly created with Wix.com

bottom of page