Insert data while upgrading module (UpgradeData) – setup script – Magento 2
- Bilal Malik
- Sep 10, 2017
- 2 min read
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
InstallSchema.php script executed while running “bin/magento setup:upgrade” , we use this features to create table structure
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.
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.

Comments