Magento: How to get attribute values used in products

后端 未结 4 1287
北荒
北荒 2021-01-30 03:43

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

4条回答
  •  轮回少年
    2021-01-30 04:08

    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 ... )

提交回复
热议问题