Add New Column to Existing Table with InstallSchema in Magento 2

databaseinstall-scriptmagento2

I'm trying to add new column to existing table in magento2

<?php

namespace Vendor\Module\Setup;

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

/**
 * @codeCoverageIgnore
 */
class InstallSchema implements InstallSchemaInterface
{

    /**
     * {@inheritdoc}
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    public function install(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;

        $installer->startSetup();

        $eavTable = $installer->getTable('eav_attribute');

        $columns = [
            'my_column' => [
                'type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER,
                'length' => '1',
                'nullable' => false,
                'comment' => 'Description of my column',
            ],
        ];

        $connection = $installer->getConnection();
        foreach ($columns as $name => $definition) {
            $connection->addColumn($eavTable, $name, $definition);
        }

        $installer->endSetup();
    }
}

php bin/magento setup:upgrade

Nothing happens

Upd 1.

If I clearly understand the goal, InstallSchema executes only when there no any values in setup table. If your module is already installed in system – you need make any changes in UpgradeSchema. That because my file didn't execute. When I renamed it to upgrade and make necessary changes – everything started working properly

Best Answer

First, I'm assuming when you say that nothing happens, you mean that the setup script runs as usual, but no errors are output and no changes were made to your database. If this isn't a correct assumption, please let me know!

When I do an upgrade to the schema, I don't do a getTable(), I think that that is superfluous.

I tested the above script with that change, and it worked, so the two troubleshooting steps I would take are to:

  1. Ensure that you have incremented the setup_version in your module.xml (or your script won't run at all)
  2. Add some obvious error in your upgrade script to see if it is running at all...if there is an error and the script is running, you will get error messages when running setup:upgrade

I hope that helps!

Related Topic