I want to add website_id column to my custom table with index and foreign key by UpgradeSchema.
It is easy to add by InstallSchema but I want to add website_id column by UpgradeSchema in my existing custom table.
Thanks
Try below code in your UpgradeSchema.php file :
<?php
/**
* Copyright © 2015 Ihor Vansach ([email protected]). All rights reserved.
* See LICENSE.txt for license details (http://opensource.org/licenses/osl-3.0.php).
*
*/
namespace Vendor\ModuleName\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
/**
* Custom Table update
*/
class UpgradeSchema implements UpgradeSchemaInterface
{
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.ExcessiveMethodLength)
*/
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
{
$installer = $setup;
$setup->startSetup();
$version = $context->getVersion();
$connection = $setup->getConnection();
$tablename = "my_custom_table";
if (version_compare($version, '1.0.6') < 0)
{
//Custom table
$connection->addColumn(
$setup->getTable($tablename),
'website_id',
[
'type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'length' => 5,
'comment' =>'Website Id',
'unsigned' => true,
'nullable' => false,
]
);
$connection->addIndex(
$setup->getTable('my_custom_table'),
$setup->getIdxName($setup->getTable('my_custom_table'),['website_id']),
['website_id']
);
$connection->addForeignKey(
$setup->getFkName($tablename,'website_id','store_website','website_id'),
$tablename,
'website_id',
$setup->getTable('store_website'),
'website_id',
Table::ACTION_CASCADE
);
}
$setup->endSetup();
}
}
Note :
ACTION_NO_ACTION
in Table parameter of Foreignkey so it will not delete the core store table data
Commented
Jul 12, 2017 at 6:06