user396716
user396716

Reputation:

Magento: How to get attribute values used in products

How I can get attribute values for some attribute that are used at least in one product?

Upvotes: 12

Views: 46249

Answers (4)

Krzysztof Chełchowski
Krzysztof Chełchowski

Reputation: 119

I needed a function to get all the values for the atribute, that are used in a specific category. I wrote this function which is not exactly what was needed by the author of the question but maybe it will help somebody.

    private function _getUsedAttribute($attributeCode, $categoryName)
{
    $category = Mage::getModel('catalog/category')->loadByAttribute('name', $categoryName);
    $attributeModel = Mage::getSingleton('eav/config')->getAttribute('catalog_product', $attributeCode);

    $sql = "SELECT DISTINCT(cpev.value)
            FROM catalog_product_entity_varchar cpev
            LEFT JOIN catalog_category_product ccp ON ccp.product_id = cpev.entity_id
            WHERE 
                cpev.attribute_id = {$attributeModel->getId()} AND
                ccp.category_id = {$category->getId()} AND
                cpev.value IS NOT NULL AND
                cpev.value <> ''";

    $data = $this->_getReadConnection()->fetchAll($sql);
    $usedAttributes = array(); 

    foreach ($data as $_item) {
        $_ids = explode(',', $_item['value']);
        foreach ($_ids as $_id) {
            if (empty($usedAttributes[$_id])) {                    
                $usedAttributes[$_id] = $attributeModel->getSource()->getOptionText($_id);
            }
        }            
    }
    natsort($usedAttributes);

    return $usedAttributes;  
}    

/**
 * read connection     
 */
protected function _getReadConnection() {
    return Mage::getSingleton('core/resource')->getConnection('core_read');
}  


print_r($this->_getUsedAttribute('device_brand', 'Phones'));

Array ( [204] => Acer [40] => Alcatel [237] => Allview [128] => Apple [225] => Asus ... )

Upvotes: 1

Vinai
Vinai

Reputation: 14182

I believe you are not trying to read an attribute value of a product model, but get a list of all used values for a specific attribute.

"Plain" attributes

Plain attributes are all attributes that don't use a select or multiselect for input, but a text or textarea field or something similar.

For these attributes use this:

// 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" attributes

If it is a select or multiselect attribute, you still need to map the option ID's to option values. That is the case if you are getting a list of integers instead of human readable labels (e.g. for the color or manufacturer attribute).

// 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

Direct DB query example

Depending on where you want to do this, here is an example of fetching the values without using a product collection. It is slightly more efficient.
Only use the following code in resource models, as thats where DB related code belongs.
This is meant as an educational example to show how to work with Magento's EAV tables.

// 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

Upvotes: 59

Sankar Subburaj
Sankar Subburaj

Reputation: 5042

If 'height' is a product attribute. We can use the below code to get the product height.

$product->getHeight();

If 'weight' is a product attribute. We can use the below code to get the product weight.

$product->getWeight();

Upvotes: 2

Shamim Ahmed
Shamim Ahmed

Reputation: 931

Use this line.

$_product->getAttributeText('attribute_code');

hope this will help

thanks

Upvotes: 14

Related Questions