1

I want to create a new upgrade schema file in magento2. I already used the install schema and upgrade schema. I need to create a new upgrade schema.

  • For which version you want? – Amit Bera May 22 at 13:15
  • What is the meaning of second time I don't get it If you already have one upgradeschema file then you have to put your version changes in that file this question seem to be unclear – Himanshu May 23 at 5:56
1

See the example UpgradeSchema.php below

<?php
    namespace XXX\YYY\Setup;

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

    class UpgradeSchema implements UpgradeSchemaInterface
    {
        public function upgrade(
            SchemaSetupInterface $setup,
            ModuleContextInterface $context
        ) {
            $installer = $setup;

            $installer->startSetup();
            if (version_compare($context->getVersion(), "1.0.0", "<")) {
            //Your upgrade script
            }
            if (version_compare($context->getVersion(), '1.0.1', '<')) {
              // your old upgrade script
            }
            $installer->endSetup();
        }
    }`

So Everytime you write a upgrade script, Compare your version with the current version and if "Less than" then proceed with your script

if (version_compare($context->getVersion(), "1.0.0", "<")) {
                //Your upgrade script
                }

Also, everytime when you add a upgrade script change the setup_version in etc/module.xml and run the upgrade command.

0

You can also use declarative schema from magento 2.3

File path: VendorName/ModuleName/etc/db_schema.xml

Install schema Example :

<?xml version="1.0"?>
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
    <table name="test" resource="default" engine="innodb" comment="CMS Block To Store Linkage Table">
        <column xsi:type="smallint" name="id" padding="6" unsigned="false" nullable="false" identity="false"/>
        <column xsi:type="varchar" name="name" nullable="true" length="255" comment="name"/>
        <constraint xsi:type="primary" referenceId="PRIMARY">
            <column name="id"/>
        </constraint>
    </table>
</schema>

Refer : Magento 2.3 Devdocs

Must read about db_schema_whitelist.json file for Backward compatibility

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.