Today, we’re going to teach you guys how to rename a database table name using declarative schema in Magento 2.3.
The latest Magento 2.3 version now directly supports table renaming. All you need to do is create a new table using the db_schema.xml file and at any time you wish it rename it, you can do so from the same db_schema.xml file.
Also read: How to Drop the Table Using Declarative Schema in Magento 2.3?
Below, we will show you how with a detailed step-by-step process.
Steps to Rename a Database Table Name using Declarative Schema in Magento 2.3
Step #1
The first step of the process is to create a db_schema.xml file in the app/code/MD/Helloworld/etc/ folder and add the following code into the file.
<?xml version="1.0"?> <!-- /** * Created By: MageDelight Pvt. Ltd. */ --> <schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="md_helloworld_new_tbl" onCreate="migrateDataFromAnotherTable(md_helloworld)" resource="default" engine="innodb" comment="MD Helloworld"> <column xsi:type="smallint" name="id" padding="6" unsigned="false" nullable="false" identity="true" comment="ID"/> <column xsi:type="varchar" name="author_name" nullable="false" length="25" comment="Name"/> <column xsi:type="varchar" name="email" nullable="false" length="25" comment="Email"/> <column xsi:type="varchar" name="description" nullable="false" length="255" comment="Descrition"/> <constraint xsi:type="primary" referenceId="PRIMARY"> <column name="id"/> </constraint> </table> </schema>
As you can see, there is an onCreate attribute being added in the <table> tag. There is also a migrateDatafromAnotherTable() function in which you can pass your old database table name as parameter value and set the new table name through the table tag name attribute as shown below.
onCreate="migrateDataFromAnotherTable(md_helloworld)
Step #2
Next, you’ll have to add schema to db_whitelist_schema.json.json file by executing the following command.
php bin/magento setup:db-declaration:generate-whitelist –module-name=MD_Helloworld
Once you’ve executed the above command, you will see that there is a db_whitelist_schema.json file created in the /MD/Helloworld/etc directory.
Step #3
Now lastly, we need to execute the following setup upgrade command after the db_whitelist_schema.json file has been created.
php bin/magento s:up
Now, check the output and you’ll see your database table name is changed.
Also read: How to Create a New Table using Declarative Schema in Magento 2.3?
Final Words…
There you have it! This is how you can rename your database table name using declarative schema in the latest Magento 2.3 version.
We hope you found this tutorial useful. If you have any questions, please share them in the comments below. And if you need our professional assistance, feel free to contact us at any time.