有没有人尝试过以 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 函数执行此操作可能会出现什么问题?
最佳答案
Magento 允许您以两种方式运行 SQL 查询:
- 使用 RAW sql 查询
- 使用magento方式
使用原始 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();
它将直接在您的表中添加索引。
使用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();
}
这里注意
$tableName = $installer->getTable('Module_name/Table_name');
您应该仔细添加模块名称和表名称。否则就不行了。欲了解更多信息,请访问here
并且不要忘记在 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>
就是这样。如果您有任何问题,请在此评论。
关于Magento - 使用升级脚本向表列添加索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27009691/