【发布时间】:2013-05-27 12:39:54
【问题描述】:
场景:您已经使用数据库迁移以编程方式创建了产品属性。几个月后,您想将该属性从 VARCHAR 更改为 TEXT 字段类型。
创建后如何更改EAV属性的字段类型,同时保留数据?
我的直觉是 Magento 的设置类不直接支持这一点,因为需要触摸无数的表、需要更新的记录以及需要从表复制到的内容表。
【问题讨论】:
标签: magento
场景:您已经使用数据库迁移以编程方式创建了产品属性。几个月后,您想将该属性从 VARCHAR 更改为 TEXT 字段类型。
创建后如何更改EAV属性的字段类型,同时保留数据?
我的直觉是 Magento 的设置类不直接支持这一点,因为需要触摸无数的表、需要更新的记录以及需要从表复制到的内容表。
【问题讨论】:
标签: magento
我不会假装这是最漂亮的解决方案,我怀疑它与数据库无关,但这是我的解决方案:
<?php
/** @var $this Mage_Eav_Model_Entity_Setup */
$this->startSetup();
$attribute_id = $this->getAttribute(
Mage_Catalog_Model_Product::ENTITY,
'your_attribute_code',
'attribute_id'
);;
if (!is_numeric($attribute_id)) {
Mage::throwException("Couldn't run migration: Unable to find attribute id");
}
/** @var Varien_Db_Adapter_Pdo_Mysql $connection */
$connection = $this->getConnection();
$connection->beginTransaction();
/**
* Copy the data from the VARCHAR table to the TEXT table.
*/
$connection->query("
INSERT INTO catalog_product_entity_text
(entity_type_id, attribute_id, store_id, entity_id, value)
SELECT
entity_type_id, attribute_id, store_id, entity_id, value
FROM catalog_product_entity_varchar
WHERE attribute_id = ?
",
array($attribute_id)
);
/**
* Update eav_attribute to use the text table instead of the varchar.
*/
$connection->query("UPDATE eav_attribute SET backend_type = 'text' WHERE attribute_id = ?", array($attribute_id));
/**
* Delete the attribute values from the VARCHAR table.
*/
$connection->query("DELETE FROM catalog_product_entity_varchar WHERE attribute_id = ?", array($attribute_id));
$connection->commit();
$this->endSetup();
【讨论】:
Mage_Eav_Entity_Setup::updateAttribute() 更改backend_type。
updateAttribute()。由于对其余表格的影响,我认为它不会支持该字段。
是的,我确认它不受支持。
您可以尝试使用 SQL 更新表,但这会很痛苦......
我会导出您的所有产品,应用修改您的属性后端表的升级脚本并重新导入您的所有产品。 这样,magento 将自动填充您的属性使用的新表 (catalog_product_entity_text)。
之后,您应该清理您的 varchar 表以删除与您的产品相关联的未使用值(这些值将永远不会被删除或更新,因为您的属性产品现在是 TEXT)
【讨论】:
catalog_product_entity_varchar 中的值 - 否则此表中的旧值将覆盖 UNION 选择中 catalog_product_entity_text 中的值。