如果我知道产品ID,而不想加载整个产品,如何获取特定的产品属性值?
如果我知道产品ID,而不想加载整个产品,如何获取特定的产品属性值?
Mage::getResourceModel('catalog/product')->getAttributeRawValue($productId, 'attribute_code', $storeId);
$product->getResource()->getAttribute($attribute_code)
->getFrontend()->getValue($product)
你可以使用
<?php echo $product->getAttributeText('attr_id') ?>
$product->getData('my_name')
。 - pavlindrom请查看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;
}
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;
}
正如您所看到的,该方法需要已加载的对象以从中获取数据(第三行)。
首先,我们必须确保所需的属性已被加载,然后输出它。使用以下代码:
$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);
$attribute = $_product->getResource()->getAttribute('custom_attribute_code');
if ($attribute)
{
echo $attribute_value = $attribute ->getFrontend()->getValue($_product);
}
您不必加载整个产品。 Magento的集合非常强大且智能。
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
当您调用getFirstItem()时,查询将被执行,并且结果产品非常简单:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
echo $_product->getData('ATTRIBUTE_NAME_HERE');
您可以通过以下方式获取属性值
$model = Mage::getResourceModel('catalog/product');
$attribute_value = $model->getAttributeRawValue($productId, 'attribute_code', $storeId);