Back to Top

Add Foreign key in Magento 2

Updated 22 February 2024

Magento-Code-Snippet-5

Here we are discussing to make a column to a foreign key in your table by patch schema.

Add the following code in your “addForeignKey.php” file:

<?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 addForeignKey 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()->addForeignKey(
                $key['FK_NAME'],
                $key['TABLE_NAME'],
                $key['COLUMN_NAME'],
                $key['REF_TABLE_NAME'],
                $key['REF_COLUMN_NAME'],
                $key['ON_DELETE']
            );
        }
      $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 [];
   }

}

After using this code foreign key will be added to your table’s column.

I hope this blog will help you with Add Foreign Key in Magento 2. 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.

Searching for an experienced
Magento 2 Company ?
Find out More

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*


1 comments

  • Aaron McMillin
  • Back to Top

    Message Sent!

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

    Back to Home