【问题标题】:Updating a Magento product attribute's database field type after creation创建后更新 Magento 产品属性的数据库字段类型
【发布时间】:2013-05-27 12:39:54
【问题描述】:

场景:您已经使用数据库迁移以编程方式创建了产品属性。几个月后,您想将该属性从 VARCHAR 更改为 TEXT 字段类型。

创建后如何更改EAV属性的字段类型,同时保留数据?

我的直觉是 Magento 的设置类不直接支持这一点,因为需要触摸无数的表、需要更新的记录以及需要从表复制到的内容表。

【问题讨论】:

    标签: magento


    【解决方案1】:

    我不会假装这是最漂亮的解决方案,我怀疑它与数据库无关,但这是我的解决方案:

    <?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();
    

    【讨论】:

    • 对于这个操作,没有“漂亮的方式”,因为它没有内置到 EAV 资源层中。唯一(完全语义)的更改是使用Mage_Eav_Entity_Setup::updateAttribute() 更改backend_type
    • @benmarks 谢谢,我将使用updateAttribute()。由于对其余表格的影响,我认为它不会支持该字段。
    • 我有 20k 种产品,默认情况下,所有产品都在多商店中分配了两个网站。如何在多商店中从选定的一个网站中删除所有产品?
    【解决方案2】:

    是的,我确认它不受支持。

    您可以尝试使用 SQL 更新表,但这会很痛苦......

    我会导出您的所有产品,应用修改您的属性后端表的升级脚本并重新导入您的所有产品。 这样,magento 将自动填充您的属性使用的新表 (catalog_product_entity_text)。

    之后,您应该清理您的 varchar 表以删除与您的产品相关联的未使用值(这些值将永远不会被删除或更新,因为您的属性产品现在是 TEXT)

    【讨论】:

    • 是的,必须删除 catalog_product_entity_varchar 中的值 - 否则此表中的旧值将覆盖 UNION 选择中 catalog_product_entity_text 中的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-10
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多