Drop or Remove a database Table in Magento 2 using the Setup folder DataPatchInterface approach.
From Magento 2.3 New Concept Setup Patch Data was introduced.
You need to create a PHP file under your module Setup/Patch/Data folder.
Lets we create the Jesadiya_DropTable module with RemoveExtraTable.php file. Our table name is image_storage_tmp is resided in the Magento 2 database.
File path: app/code/Jesadiya/DropTable/Setup/Patch/Data/RemoveExtraTable.php
<?php declare(strict_types=1); /** * RemoveExtraTable Patch Class * * Setup Patch data class to remove * table image_storage_tmp */ namespace Jesadiya\DropTable\Setup\Patch\Data; use Magento\Framework\Setup\SchemaSetupInterface; use Magento\Framework\Setup\Patch\DataPatchInterface; /** * Class RemoveExtraTable */ class RemoveExtraTable implements DataPatchInterface { /** * table entity value */ const IMAE_STORAGE = 'image_storage_tmp'; /** * @var SchemaSetupInterface */ private $schemaSetup; public function __construct( SchemaSetupInterface $schemaSetup ) { $this->schemaSetup = $schemaSetup; } /** * {@inheritDoc} */ public static function getDependencies(): array { return []; } /** * {@inheritDoc} */ public function getAliases(): array { return []; } /** * This method used to Remove older extra table * * @return void */ public function apply(): void { $installer = $this->schemaSetup; $installer->startSetup(); if ($installer->tableExists(self::IMAE_STORAGE)) { $installer->getConnection()->dropTable($installer->getTable(self::IMAE_STORAGE)); } $installer->endSetup(); } }
In the above code we have used SchemaSetupInterface to call dropTable() function.
In the script, We first checking if the table exists in the database or not, If the table exists, remove it from the database otherwise skip it.
Run bin/magento setup:upgrade command to remove a table from the database.