当前位置: 技术文章>> magento2中的UpgradeSchema脚本-upgradeschema.php介绍

文章标题:magento2中的UpgradeSchema脚本-upgradeschema.php介绍
  • 文章分类: Magento
  • 28942 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


UpgradeSchema脚本用于创建新表或向现有表添加列。.

假设它在每次setup:upgrade上运行,其中setup_module.schema_version低于<VendorName>/<ModuleName>/etc/module.xml下的setup_version,

我们负责控制特定版本的代码。这通常是通过if-ed-version_compare方法来完成的。为了更好地演示这一点,让我们创建<MAGELICIOUS_DIR>/Core/Setup/UpgradeSchema.phpfile,其中包含以下内容:

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) {
        $setup - > startSetup();
        if (version_compare($context - > getVersion(), '2.0.2') < 0) {
            $this - > upgradeToVersionTwoZeroTwo($setup);
        }
        $setup - > endSetup();
    }
    private function upgradeToVersionTwoZeroTwo(SchemaSetupInterface $setup) {
        echo 'UpgradeSchema->upgradeToVersionTwoZeroTwo()'.PHP_EOL;
    }
}

这里的if-ed-version_compare如下:如果当前模块版本等于2.0.2,则执行upgradeToVersionTwoZeroTwo方法。

如果我们要发布模块的更新版本,我们需要正确地提升<VendorName>/<ModuleName>/etc/module.xml的setup_version,否则UpgradeSchema就没有多大意义。

同样,我们应该始终确保针对特定的模块版本,从而避免在每次版本更改时执行代码。

当涉及到UpgradeSchema脚本时,数据库适配器实例的以下方法以及前面提到的方法将是令人感兴趣的:dropColumn:从表中删除列


dropForeignKey:从表删除外键

dropIndex:从表上删除索引

dropTable:从数据库中删除表

ModifyColumn:修改列定义



推荐文章