Add custom column to table via patch in Magento 2 - Magesan

Add custom column to table via patch in Magento 2

Add custom column to table via patch in Magento 2

You need to create a file at path : Magesan\Extension\Setup\Patch\Schema\DbModifier.php

DbModifier.php have the below code :

<?php
 
namespace Magesan\Extension\Setup\Patch\Schema;
 
use Magento\Framework\Setup\Patch\SchemaPatchInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
use Magento\Framework\DB\Ddl\Table;
 
class DbModifier implements SchemaPatchInterface
{
    const COLUMN_NAME = "custom";
    const TABLE_NAME  = "sales_order";
 
    /**
     * @var ModuleDataSetupInterface
     */
    protected $moduleDataSetup;
 
    /**
     * __construct
     *
     * @param ModuleDataSetupInterface $moduleDataSetup
     */
    public function __construct(
        ModuleDataSetupInterface $moduleDataSetup
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
    }
 
    /**
     * {@inheritdoc}
     */
    public function apply()
    {
        $this->moduleDataSetup->startSetup();
 
        $setupConnection = $this->moduleDataSetup->getConnection();
        $setupConnection->addColumn(
            $this->moduleDataSetup->getTable(self::TABLE_NAME),
            self::COLUMN_NAME,
            [
                "type"     => Table::TYPE_BOOLEAN,
                "comment"  => "Custom",
                "label"    => "Custom",
                "nullable" => true,
                "default"  => 0,
            ]
        );
 
        $this->moduleDataSetup->endSetup();
    }
 
    /**
     * {@inheritdoc}
     */
    public static function getDependencies()
    {
        return [];
    }
 
    /**
     * {@inheritdoc}
     */
    public function getAliases()
    {
        return [];
    }
}

Happy Coding…

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*
You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>