Webkul
Services
Technologies Bagisto QloApps
iOS Android SAP BigCommerce Wix
Trusted by
Samsung Intel Toyota Walmart Disney Nokia Nestlé Decathlon
See all customers
Back to Top
DEV

Delete an existing Foreign key in Magento 2 Installer

If you want to Delete an existing foreign key from a table by using a patch file, then you can use the following code:

<?php

namespace Webkul\Test\Setup\Patch\Schema;

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

class DropExistingForeignKey implements SchemaPatchInterface, PatchVersionInterface
{

    private $schemaSetup;

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

    public function apply()
    {

      $this->schemaSetup->startSetup();
      $tableName = $this->schemaSetup->getTable('wk_sellerstorepickup_store_store_view');
      
      $existingForeignKeys = $this->schemaSetup->getConnection()->getForeignKeys($tableName);
        foreach ($existingForeignKeys as $key) {
            $this->schemaSetup->getConnection()->dropForeignKey($key['TABLE_NAME'], $key['FK_NAME']);
      }
      $this->schemaSetup->endSetup();
    }
    /**
    * Get dependencies
    */
   public static function getDependencies()
   {
       return [];
   }

     /**
     * {@inheritdoc}
     */
    public static function getVersion()
    {
        return '2.0.4';
    }

   /**
    * Get Aliases
    */
   public function getAliases()
   {
       return [];
   }

}

If you want to add a foreign key in your table then refer following blog:

Add Foreign Key In Magento2

I hope this blog will help you with Delete an existing Foreign key in Magento 2 Installer. You may also check our wide range of best Magento 2 Extensions.

Please reach out to our team via a support ticket if you have any queries.

Try this and if you have any queries then just comment below 🙂

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home