Magento – Magento 2 : Upgrade Script Alter Column with Foreign Key via API

-setupdatabaseforeign keymagento2

In a Magento 2 upgrade script, I wanted to modify (alter) a column to change its comment.

Now that column has a foreign key. Whenever I call the modify column method of the setup class, Mysql reports an error that it can't modify the column because of a foreign key constraint.

What is the correct syntax in the Magento 2 setup-classes API to modify a column's comment where that column has a foreign key constraint?

Code-example of the modify part, type and nullable is exactly the same as for the column when it was created, only the comment is changed. It results in the foreign key constraints error; from a src/app/code/Vendor/ExamplePlugin/Setup/UpgradeSchema.php file:

...

        $connection->modifyColumn(
            $setup->getTable('example_list_item'),
            'list_id',
            [
                'type' => Table::TYPE_INTEGER,
                'nullable' => false,
                'comment' => 'ExampleListID'
            ]
        );

...

Best Answer

I have changed Magento field length using this code. Hope this will help you.

FilePath: [VenderName][ExtensionName]\Setup\InstallSchema.php;

namespace  [VenderName]\[ExtensionName]\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;

    class InstallSchema implements InstallSchemaInterface
    {
        public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
        {
            $setup->startSetup();

      $setup->getConnection()->changeColumn(
       $setup->getTable('catalog_product_option_type_price'),
       'price_type',
       'price_type',
       [
        'type' => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
        'length' => 12
       ]
      );
        }
    }
Related Topic