
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.
Try this and if you have any queries then just comment below 🙂
1 comments