How To

Magento 2: Truncate Table from Database using Data Patch Interface

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

<?php 
namespace Vendor\Extension\Setup\Patch\Schema;

use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\Patch\PatchVersionInterface;
use Magento\Framework\Setup\Patch\SchemaPatchInterface;

class TruncateTable implements SchemaPatchInterface, PatchVersionInterface
{ 
    private $schemaSetup;

    public function __construct(
        SchemaSetupInterface $schemaSetup
    )
    {
        $this->schemaSetup = $schemaSetup;
    }

    public function apply()
    {
        $this->schemaSetup->startSetup();
        $tableName = $this->schemaSetup->getTable('Persons');  // Enter Your Table Name 
        if ($this->schemaSetup->tableExists($tableName))
        {
            $this->schemaSetup->getConnection()->truncateTable($tableName);
        }
        $this->schemaSetup->endSetup();
    }

    public static function getDependencies()
    {
        return [];
    }

    public static function getVersion()
    {
        return '1.0.3';
        //  please enter version upper than current 
        // example : current version : 1.0.1 -> use : 1.0.2 
    }

    public function getAliases()
    {
        return [];
    }
}

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

php bin/magento setup:upgrade

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

<?php 
 
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
 
$bootstraps = Bootstrap::create(BP, $_SERVER);
$object_Manager = $bootstraps->getObjectManager();
 
$app_state = $object_Manager->get('\Magento\Framework\App\State');
$app_state->setAreaCode('frontend');
 
try
{
    $bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $appState = $objectManager->get('\Magento\Framework\App\State');
    $appState->setAreaCode('frontend');
 
    $objectManager= \Magento\Framework\App\ObjectManager::getInstance();
    
    //  enter your Extension Factory Class
    $locationTruncate = $objectManager->get('\Vendor\Extension\Model\LocationFactory')->create();    
    $connection = $locationTruncate->getCollection()->getConnection();
    $tableName = $locationTruncate->getCollection()->getMainTable();
    $connection->truncateTable($tableName);
}
catch(\Exception $e)
{
    print_r($e->getMessage());
}

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]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Enhancing Web Application Security with Laravel’s Built-In Features

In today’s digital landscape, web application security is paramount. As a powerful PHP framework, Laravel…

1 day ago

Magento 2 Extensions Digest October 2024 (New Release & Updates)

October was an exciting month for MageComp! From significant updates across our Magento 2 extension…

1 day ago

Improving Error Handling and Transition Management in Remix with useRouteError and useViewTransitionState

In modern web development, seamless navigation and state management are crucial for delivering a smooth…

1 week ago

Magento Open Source 2.4.8-Beta Release Notes

Magento Open Source 2.4.8 beta version released on October  8, 2024. The latest release of…

1 week ago

How to Create Catalog Price Rule in Magento 2 Programmatically?

Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…

1 week ago

Top 10 Tips to Hire Shopify Developers

As the world of eCommerce continues to thrive, Shopify has become one of the most…

2 weeks ago