Magento - 使用升级脚本向表列添加索引

Man*_*P M 2 magento

是否有人试图以magento方式向已经存在的数据库表中的列添加索引?

当我尝试使用时

$ table-> addIndex('index_name','field_name','index_type'),它无法正常工作.

最后我尝试了正常的ALTER TABLE查询

$ installer-> run("ALTER TABLE table_name ADD INDEX index_name(field_name)");

我得到了它的工作.

问题是使用magento表DDL函数执行此操作可能会出现什么问题?

Ela*_*san 8

Magento允许您以两种方式运行SQL查询:

  1. 使用RAW SQL查询
  2. 使用magento方式

使用RAW SQL查询

您可以直接运行SQL查询.在您的方案中,

<?php
$installer = $this;
$installer->startSetup();
$sql=<<<SQLTEXT
ALTER TABLE table_name ADD INDEX index_name(field_name);
SQLTEXT;

$installer->run($sql);
$installer->endSetup();
Run Code Online (Sandbox Code Playgroud)

它会直接在表中添加索引.

使用magento方式

使用magento的方式非常复杂.就像是,

<?php

$installer = $this;
$installer->startSetup();

$tableName = $installer->getTable('Module_name/Table_name');
// Check if the table already exists
if ($installer->getConnection()->isTableExists($tableName)) {
$table = $installer->getConnection();

$table->addIndex(
  $installer->getIdxName(
    'your_namespace/your_table',
    array(
      'column1',
      'column2',
      'column3',
    ),
    Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE
  ),
  array(
    'column1',
    'column2',
    'column3',
  ),
  array('type' => Varien_Db_Adapter_Interface::INDEX_TYPE_UNIQUE)
)
$installer->endSetup();
}
Run Code Online (Sandbox Code Playgroud)

在这里注意

 $tableName = $installer->getTable('Module_name/Table_name'); 
Run Code Online (Sandbox Code Playgroud)

您应该仔细添加模块名称和表名称.其他明智的做法并不奏效.有关更多信息,请转到此处

并且不要忘记在您config.xml的数据库中添加以下内容以获取对数据库的身份验证

<global>
...
<resources>
      <modulename_setup>
        <setup>
          <module>Packagename_ModuleName</module>
        </setup>
        <connection>
          <use>core_setup</use>
        </connection>
      </modulename_setup>
      <modulename_write>
        <connection>
          <use>core_write</use>
        </connection>
      </modulename_write>
      <modulename_read>
        <connection>
          <use>core_read</use>
        </connection>
      </modulename_read>
    </resources>
...
</global>
Run Code Online (Sandbox Code Playgroud)

而已.如果您有任何疑问,请在这里发表评论.