Hello Magento Friends,

Today’s tutorial will teach you How to Truncate Table from Database using Data Patch in Magento 2. Previously I have also explained How to Drop Table from Database using Data Patch in Magento 2.

Truncating removes the data inside the table but not the table. In Magento 2, you can truncate table from database using data patch interface and root script.

So, let us look at both ways to truncate table from database in Magento 2.

Steps to Truncate Table from Database using Data Patch Interface in Magento 2:

Here we will truncate the table from the database using 2 methods.

Method 1: Truncate Table using Data Patch Interface

Step 1: Create the TruncateTable.php file inside the Setup folder at the below path.

app\code\Vendor\Extension\Setup\Patch\Schema\TruncateTable.php

And add the code as follows

Step 2: Run the below command to remove a table from the database.

Note: Please check whether your patch_name exists in the “patch_list” database table or not. If it exists, please remove the column.

Method 2: Truncate Table using Root Script

We will use the factory class to truncate the table. Let’s see how we can do that.

Step 1: Create a truncatetable.php file in your Magento root directory. Here we need to use the model factory class to truncate the table.

Add the code as follows

Conclusion:

This way, you can Truncate Table from Database using Data Patch Interface in Magento 2. If you face any hardship, share it with me through the comment section. Keep in touch with us for the latest Magento tutorials.

Happy Coding!

Click to rate this post!
[Total: 2 Average: 5]