Magento: как получить значения атрибутов, используемые в продуктах - PullRequest
12 голосов
/ 05 марта 2012

Как я могу получить значения атрибутов для некоторых атрибутов, которые используются хотя бы в одном продукте?

Ответы [ 4 ]

59 голосов
/ 05 марта 2012

Я полагаю, что вы не пытаетесь прочитать значение атрибута модели продукта, но получаете список всех используемых значений для определенного атрибута.

"Обычные" атрибуты

Обычные атрибуты - это все атрибуты, которые не используют 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
14 голосов
/ 05 марта 2012

Используйте эту строку.

$_product->getAttributeText('attribute_code');

надеюсь, это поможет

спасибо

2 голосов
/ 05 марта 2012

Если «высота» является атрибутом товара.Мы можем использовать приведенный ниже код для получения высоты продукта.

$product->getHeight();

Если «вес» является атрибутом продукта.Мы можем использовать приведенный ниже код, чтобы получить вес продукта.

$product->getWeight();
1 голос
/ 05 августа 2015

Мне нужна была функция, чтобы получить все значения для атрибута, которые используются в определенной категории.Я написал эту функцию, которая не совсем то, что нужно автору вопроса, но, возможно, она кому-нибудь поможет.

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...