Change Table Column Nullable Definition Using Declarative Schema – Magento2 Guide

db-schemamagento2magento2.4

I have added a table using declarative schema given below:

<table name="trade_item_brand_category">
        <column xsi:type="int" name="id" padding="10" unsigned="true" nullable="false" identity="true" comment="ID"/>
        <column xsi:type="varchar" name="item_pool" nullable="false" length="100" comment="Brand"/>
        <column xsi:type="datetime" name="new_brand_approved_time" on_update="false" nullable="false" comment="Brand Approval Time"/>
        
        <constraint xsi:type="primary" referenceId="PRIMARY">
           <column name="id"/>
        </constraint>
</table>

Now I want to change nullable definition of new_brand_approved_time column from false to true. I have modified this db_schema.xml file as give below

 <column xsi:type="datetime" name="new_brand_approved_time" nullable="true" comment="Brand Approval Time"/>
            

After running setup:upgrade I am checking new_brand_approved_time field but nullable is still false for this column.

I have also tried the old M2 approach of UpgradeSchema as given below, still nullable option is not changing

<?php

namespace Vendor\Module\Setup;

use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\DB\Ddl\Table;

class UpgradeSchema implements UpgradeSchemaInterface
{

    public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context)
    {
        $installer = $setup;
        $installer->startSetup();
        if ($installer->getConnection()->tableColumnExists('trade_item_brand_category', 'new_brand_approved_time')) {
            $definition = [
                'nullable' => true,
            ];
            $installer->getConnection()->modifyColumn(
                $setup->getTable('trade_item_brand_category'),
                'new_brand_approved_time',
                $definition
            );
        }
    }
}

When I run setup:upgrade, db_schema.xml file is being executed. I have testing it by adding a new column to the table but nullable option is not changing for column new_brand_approved_time.

Best Answer

I have this issue today too. Not sure why Magento 2 does not find the nullable attribute has been changed.

I fixed it by updating the comment attribute to something else and run bin/magento setup:upgrade --keep-generated.

Hope this help someone.

Related Topic