UpgradeData Magento 2

The UpgradeData will be run during module upgrade and its used to alter the table structure.

The module upgrade script will run when you run the following command line

php bin/magento setup:upgrade

We will need to check the attribute setup_version in module.xml at app/code/PHPCodez/v/etc/ and separate the script by each version.

In this example, we will change the attrubute setup_version to higher level.

File: app/code/PHPCodez/First/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="PHPCodez_First" setup_version="0.0.2">
 </module>
</config>

File : app/code/PHPCodez/First/Setup/UpgradeData .php

<?php

namespace PHPCodez\First\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)
 {
 $setup->startSetup();

if (version_compare($context->getVersion(), '0.0.4', '<=')) {
 $setup->getConnection()->query("INSERT INTO phpcodez_post SET name = 'Post 1'");
 }

$setup->endSetup();
 }
}

Leave a Reply

Your email address will not be published. Required fields are marked *