0

I know there are few posts regarding how to add new column to existing table in Magento 2. My concern is if I already have a webshop that is running, can I still add a new column to a table?

for example, I want to add a new column to the table sales_order_item in a webshop database that already has a lot of data existing.

0

You need to use below cod in your setup script of your custom module

<?php

namespace Vendor\Modulename\Setup;


use Magento\Sales\Setup\SalesSetupFactory;
use Magento\Eav\Model\Entity\Attribute\SetFactory as AttributeSetFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

/**
 * InstallData
 *
 * @codeCoverageIgnore
 */
class InstallData implements InstallDataInterface
{


    /**
     * SalesSetupFactory
     *
     * @var SalesSetupFactory
     */
    protected $salesSetupFactory;



    /**
     * Constructor
     * @param SalesSetupFactory $salesSetupFactory
     */
    public function __construct(
        SalesSetupFactory $salesSetupFactory
    ) {
        $this->salesSetupFactory = $salesSetupFactory;
    }


    /**
     * Install
     *
     * @param ModuleDataSetupInterface $setup
     * @param ModuleContextInterface $context
     */
    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {

        /** @var \Magento\Sales\Setup\SalesSetup $salesInstaller */
        $salesInstaller = $this->salesSetupFactory->create(['resourceName' => 'sales_setup', 'setup' => $setup]);

        $salesInstaller->addAttribute('order_item', 'test', ['type' => \Magento\Framework\DB\Ddl\Table::TYPE_INTEGER, 'length'=> 10, 'visible' => false,'nullable' => true,]);
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.