Change column name for database table Magento 2?

In Magento 2 if you want to change/rename the existing column/field from the table.

Let’s assume I have a table custom_table1 and the table containing field post_user.

So what I’m going to do is change table field post_user to the author .

My module current version in 1.0.1. So Upgrade the setup_version number of the module.So I have added new version 1.0.2 in module.xml file

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="MageChallenge_SetupData" setup_version="1.0.2">
    </module>
</config>

Create UpgradeSchema.php file under the Setup folder in your module.
File Path: app/code/MageChallenge/SetupData/Setup/UpgradeSchema.php

<?php
namespace MageChallenge\SetupData\Setup;

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

/**
 * Class UpgradeSchema
 * @package MageChallenge\SetupData\Setup
 */
class UpgradeSchema implements UpgradeSchemaInterface
{
    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        if (version_compare($context->getVersion(), '1.0.2', '<')) {
            $setup->getConnection()->changeColumn(
                $setup->getTable('custom_table1'),
                'post_user',
                'author',
                [
                    'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                    'length' => 150,
                    'comment' => 'Author Name'
                ]
            );
        }
        $setup->endSetup();
    }
}

Finally Run php bin/magento setup:upgrade command from the root directory to update the table.

Also, you can check how to wark with InstallSchema in Magento 2

click here

Have a nice day 🙂

Latest posts by Chathura Janaka Liyanage (see all)

2 thoughts on “Change column name for database table Magento 2?

  1. I happen to be writing to make you understand what a useful experience our princess went through visiting yuor web blog. She realized too many things, with the inclusion of what it is like to possess an incredible teaching style to make the others without problems thoroughly grasp various very confusing topics. You undoubtedly surpassed visitors’ expected results. Thanks for supplying those warm and friendly, trustworthy, revealing not to mention unique tips on your topic to Tanya.

Leave a Reply