我从中得到了这个代码 这里, ,它起作用。但是,有一部分我不完全得到。请参阅[a]和[b]行。

public function attributeValueExists($attCode, $attributeValue)
{
    $attributeModel = Mage::getModel('eav/entity_attribute');
    $attributeOptionModel = Mage::getModel('eav/entity_attribute_source_table') ;

    $attributeId = $attributeModel->getIdByCode('catalog_product', $attCode);    // [A]
    $attribute = $attributeModel->load($attributeId);    // [B]

    $attributeTable = $attributeOptionModel->setAttribute($attribute);
    $options = $attributeOptionModel->getAllOptions(false);

    foreach($options as $option) {
        if ($option['label'] == $attributeValue) {
            return $option['value'];
        }
    }

    return false;
}

从线[a]和[b]获得的变量, $attributeTable, ,似乎不使用。但是,如果我评论这两行,则代码不起作用。这些线实际上是在做什么,为什么要做 $attributeTable 为了?

有帮助吗?

解决方案

当您说它们“未使用”时,您会误会。他们实际上是:

此行获取$ attibuteId:

$attributeId = $attributeModel->getIdByCode('catalog_product', $attCode);    // [A]

该行加载属性:

$attribute = $attributeModel->load($attributeId);    // [B]

该行使用$ attributeoptionmodel上的设置器中的$属性:

$attributeTable = $attributeOptionModel->setAttribute($attribute);

GetAllOptions要求已设置属性:

$options = $attributeOptionModel->getAllOptions(false);

我认为您被绊倒的位置是不使用$属性,但这只是Setter方法的返回值。 Magento中的魔术设置器总是返回父对象 这样您就可以构建一个流利的界面.

其他提示

此函数返回属性值,该属性是选择或多个选择。我们可以类似地编写此功能:

public function attributeValueExists($attCode, $attributeValue)
{
    $attributeModel = Mage::getModel('eav/entity_attribute');
    $attributeOptionModel = Mage::getModel('eav/entity_attribute_source_table') ;

    //retrieve attribute_id using attribute_code
    $attributeId = $attributeModel->getIdByCode('catalog_product', $attCode);    // [A] 
    //load attribute model using attribute_id
    $attribute = $attributeModel->load($attributeId);    // [B] 

    $options = $attributeOptionModel->setAttribute($attribute)->getAllOptions(false);

    foreach($options as $option) {
        if ($option['label'] == $attributeValue) {
            return $option['value'];
        }
    }

    return false;
}

但这是很长的路要走,我们可以使用此片段来检索属性值:

 public function attributeValueExists($attCode, $attributeValue)
 {
     /**
     * @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract
     */
    $attribute = Mage::getModel('catalog/resource_eav_attribute')
        ->loadByCode(Mage_Catalog_Model_Product::ENTITY, $attCode);

    $options   = $attribute->getSource()->getAllOptions();
    foreach ($options as $option) {
        if ($option['label'] == $attributeValue) {
            return $option['value'];
        }
    }
    return false;
 }
许可以下: CC-BY-SA归因
scroll top