How to rename an existing custom table in Magento 2?
-
16-03-2021 - |
Question
I created a table with name "Redeem_blanace" using InstallSchema.php as:
class InstallSchema implements InstallSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
$table = $setup->getConnection()->newTable($setup->getTable('Redeem_balance')
)->addColumn(
'transaction_id',
Table::TYPE_INTEGER,
null,
['identity' => true, 'unsigned' => true, 'nullable' => false, 'primary' =>true],
'Transaction_Id'
)->addColumn(
'gift_code',
Table::TYPE_TEXT,
255,
['nullable' => true],
'Gift_Code'
)->addColumn(
'redeem_amount',
\Magento\Framework\DB\Ddl\Table::TYPE_DECIMAL,
'20,4',
['nullable' => false, 'default' => 0],
'Redeem_Amount'
)->addColumn(
'date_expires',
Table::TYPE_TEXT,
null,
['nullable' => true],
'Date_Expires'
)->addColumn(
'expired_amount',
Table::TYPE_INTEGER,
null,
['unsigned' => false, 'nullable' => false],
'Expired_Amount'
)->addIndex(
$setup->getIdxName('Redeem_balance', ['transaction_id']),
['transaction_id']
)->setComment(
'Redeem Balance Tracking Table'
);
$setup->getConnection()->createTable($table);
$setup->endSetup();
}
}
I wanted to change the table name to "pme_customerbalance" How can I do this ?
Solution
You can create UpgradeSchema.php file in your module and add below content in that file
app/code/Vendor/Module/Setup/UpgradeSchema.php
<?php
namespace Vendor\Module\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface
{
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$setup->startSetup();
if (version_compare($context->getVersion(), '1.0.2', '<')) {
$setup->getConnection()->renameTable($setup->getTable('Redeem_balance'), $setup->getTable('pme_customerbalance'));
}
$setup->endSetup();
}
}
You can change module version based on your module.
Hope this will help you!
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange