Magento产品属性获得价值

Den*_*hov 82 attributes product magento

如果我知道产品ID而没有加载整个产品,如何获得具体的产品属性值?

小智 140

Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);
Run Code Online (Sandbox Code Playgroud)

  • 对于那些重要的人:这种方法仅适用于1.6+ (2认同)

Luc*_*ops 39

我知道的一种方式:

$product->getResource()->getAttribute($attribute_code)
        ->getFrontend()->getValue($product)
Run Code Online (Sandbox Code Playgroud)

  • @Mr_Green因为这是Magento.没有'为什么'得到一个合理的答案. (25认同)
  • 我是magento的新手..为什么两次使用`$ product`? (4认同)
  • 谢谢.这就是我在寻找的东西. (3认同)

Vis*_*hal 26

您可以使用

<?php echo $product->getAttributeText('attr_id')  ?> 
Run Code Online (Sandbox Code Playgroud)

  • 此代码仅在产品模型包含属性值时才起作用,当您只知道产品ID时它将不起作用 (3认同)
  • 这段代码很好用.我搜索了很多博客,但除此之外没有一个代码适合我.非常好. (2认同)

Tyl*_* V. 9

请参阅Daniel Kocherga的答案,因为在大多数情况下它会对你有用.

除了获取属性值的方法之外,有时您可能希望获得select或的标签multiselect.在这种情况下,我创建了这个方法,我存储在一个帮助器类中:

/**
 * @param int $entityId
 * @param int|string|array $attribute atrribute's ids or codes
 * @param null|int|Mage_Core_Model_Store $store
 *
 * @return bool|null|string
 * @throws Mage_Core_Exception
 */
public function getAttributeRawLabel($entityId, $attribute, $store=null) {
    if (!$store) {
        $store = Mage::app()->getStore();
    }

    $value = (string)Mage::getResourceModel('catalog/product')->getAttributeRawValue($entityId, $attribute, $store);
    if (!empty($value)) {
        return Mage::getModel('catalog/product')->getResource()->getAttribute($attribute)->getSource()->getOptionText($value);
    }

    return null;
}
Run Code Online (Sandbox Code Playgroud)


小智 8

没有加载产品模型似乎不可能获得价值.如果你看一下文件app/code/core/Mage/Eav/Model/Entity/Attribute/Frontend/Abstract.php,你会看到方法

public function getValue(Varien_Object $object)
{
    $value = $object->getData($this->getAttribute()->getAttributeCode());
    if (in_array($this->getConfigField('input'), array('select','boolean'))) {
        $valueOption = $this->getOption($value);
        if (!$valueOption) {
            $opt = new Mage_Eav_Model_Entity_Attribute_Source_Boolean();
            if ($options = $opt->getAllOptions()) {
                foreach ($options as $option) {
                    if ($option['value'] == $value) {
                        $valueOption = $option['label'];
                    }
                }
            }
        }
        $value = $valueOption;
    }
    elseif ($this->getConfigField('input')=='multiselect') {
        $value = $this->getOption($value);
        if (is_array($value)) {
            $value = implode(', ', $value);
        }
    }
    return $value;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,此方法需要加载对象从中获取数据(第3行).


小智 5

首先,我们必须确保加载所需的属性,然后输出它.用这个:

$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);
Run Code Online (Sandbox Code Playgroud)