Подтвердить что ты не робот

Magento: как получить значения атрибутов, используемые в продуктах

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

4b9b3361

Ответ 1

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

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

Обычные атрибуты - это все атрибуты, которые не используют select или multiselect для ввода, но поле text или textarea или что-то подобное.

Для этих атрибутов используйте это:

// 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 to option labels
$usedAttributeValues = $attributeModel->getSource()->getOptionText(
    implode(',', $usedAttributeValues)
);

// $usedAttributeValues now contains an array of used values in human readable format

Пример запроса прямого DB

В зависимости от того, где вы хотите это сделать, приведен пример получения значений без использования коллекции продуктов. Это немного более эффективно.
Используйте только следующий код в моделях ресурсов, так как это касается кода, связанного с DB.
Это подразумевается как образовательный пример, показывающий, как работать с таблицами Magento EAV.

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

Ответ 2

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

$_product->getAttributeText('attribute_code');

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

спасибо

Ответ 3

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

$product->getHeight();

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

$product->getWeight();

Ответ 4

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

    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'));

Массив (   [204] = > Acer   [40] = > Alcatel   [237] = > Allview   [128] = > Apple   [225] = > Asus ...)