magentomagento-2.3

Update field of database


I have this code to udpdate max length of an attribute

class UpgradeData implements UpgradeDataInterface
{
    public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        if ($context->getVersion()
            && version_compare($context->getVersion(), '1.0.2') < 0
        ) {
            $table = $setup->getTable('eav_attribute');
            $setup->getConnection()
                ->update($table, ['frontend_class' => 'validate-length maximum-length-70'], 'attribute_id = 73');
        }
        $setup->endSetup();
    }
}

It works fine bu instad of attribute_id = 73 I want to put attribute_code= name but it does not work.


Solution

  • Try this

    class UpgradeData implements UpgradeDataInterface
    {
        /**
         * @var \Magento\Eav\Setup\EavSetupFactory
         */
        private $eavSetupFactory;
        
        public function __construct(\Magento\Eav\Setup\EavSetupFactory $eavSetupFactory)
        {
             $this->eavSetupFactory = $eavSetupFactory;
        }
        public function upgrade(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
        {
            $setup->startSetup();
            if ($context->getVersion()
                && version_compare($context->getVersion(), '1.0.2') < 0
            ) {
                $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
                $this->eavSetup->updateAttribute(
                    'catalog_product',
                    'ATTRIBUTE_CODE_GOES_HERE',
                    'frontend_class',
                    'validate-length maximum-length-70'
                );
            }
            $setup->endSetup();
        }
    }
    

    Watch out for typos. I didn't check the code.