Я полагаю, что вы не пытаетесь прочитать значение атрибута модели продукта, но получаете список всех используемых значений для определенного атрибута.
"Обычные" атрибуты
Обычные атрибуты - это все атрибуты, которые не используют select
или multiselect
для ввода, но содержат текстовое или текстовое поле или что-то подобное.
Для этих атрибутов используйте это:
// specify the attribute code
$attributeCode = 'name';
// build and filter the product collection
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter($attributeCode, array('notnull' => true))
->addAttributeToFilter($attributeCode, array('neq' => ''))
->addAttributeToSelect($attributeCode);
// get all distinct attribute values
$usedAttributeValues = array_unique($products->getColumnValues($attributeCode));
Атрибуты "Option"
Если это атрибут select
или multiselect
, вам все равно необходимо сопоставить идентификаторы опции со значениями опции. Это имеет место, если вы получаете список целых чисел вместо удобочитаемых ярлыков (например, для атрибута color
или manufacturer
).
// specify the select or multiselect attribute code
$attributeCode = 'color';
// build and filter the product collection
$products = Mage::getResourceModel('catalog/product_collection')
->addAttributeToFilter($attributeCode, array('notnull' => true))
->addAttributeToFilter($attributeCode, array('neq' => ''))
->addAttributeToSelect($attributeCode);
$usedAttributeValues = array_unique($products->getColumnValues($attributeCode));
// ---- this is the different part compared to the previous example ----
// fetch the attribute model
$attributeModel = Mage::getSingleton('eav/config')
->getAttribute('catalog_product', $attributeCode);
// map the option id's to option labels
$usedAttributeValues = $attributeModel->getSource()->getOptionText(
implode(',', $usedAttributeValues)
);
// $usedAttributeValues now contains an array of used values in human readable format
Пример прямого запроса к БД
В зависимости от того, где вы хотите сделать это, вот пример извлечения значений без использования набора продуктов. Это немного более эффективно.
Используйте только следующий код в моделях ресурсов, так как он относится к коду, связанному с БД.
Это учебный пример, демонстрирующий работу с таблицами EAV в Magento.
// specify the attribute code
$attributeCode = 'color';
// get attribute model by attribute code, e.g. 'color'
$attributeModel = Mage::getSingleton('eav/config')
->getAttribute('catalog_product', $attributeCode);
// build select to fetch used attribute value id's
$select = Mage::getSingleton('core/resource')
->getConnection('default_read')->select()
->from($attributeModel->getBackend()->getTable(), 'value')
->where('attribute_id=?', $attributeModel->getId())
->distinct();
// read used values from the db
$usedAttributeValues = Mage::getSingleton('core/resource')
->getConnection('default_read')
->fetchCol($select);
// map used id's to the value labels using the source model
if ($attributeModel->usesSource())
{
$usedAttributeValues = $attributeModel->getSource()->getOptionText(
implode(',', $usedAttributeValues)
);
}
// $usedAttributeValues now contains an array of used option value labels