2011-08-18 92 views
7

我的屬性代碼數組,我需要得到的值:是否有更簡單的方法來獲取屬性的前端值?

$attributeId = Mage::getResourceModel('eav/entity_attribute') 
    ->getIdByCode('catalog_product', $attribute_code); 
$attribute = Mage::getModel('catalog/resource_eav_attribute') 
    ->load($attributeId); 
$value = $attribute->getFrontend()->getValue($product); 

簡單:

$attributes = array(
    'Category'   => 'type', 
    'Manufacturer'  => 'brand', 
    'Title'    => 'meta_title', 
    'Description'  => 'description', 
    'Product Link'  => 'url_path', 
    'Price'    => 'price', 
    'Product-image link' => 'image', 
    'SKU'    => 'sku', 
    'Stock'    => 'qty', 
    'Condition'   => 'condition', 
    'Shipping cost'  => 'delivery_cost'); 

通過產品收集我得到的屬性的前端值,像這樣的迭代之後使用$product->getDate($attribute)將無法​​使用下拉菜單和多選,它只返回它們的id而不是它們的前端值。

儘管上面的代碼有效,但獲取值似乎還有很長的路要走,但更重要的是它運行速度很慢。有沒有更快捷/更明智的方式來獲得產品屬性的前端值?

編輯
我現在有以下(處理特殊情況下,像imageqty後),這是對眼睛更容易一點,似乎可以跑得快一點(雖然我不知道爲什麼):

$inputType = $product->getResource() 
        ->getAttribute($attribute_code) 
        ->getFrontend() 
        ->getInputType(); 

switch ($inputType) { 
case 'multiselect': 
case 'select': 
case 'dropdown': 
    $value = $product->getAttributeText($attribute_code); 
    if (is_array($value)) { 
     $value = implode(', ', $value); 
    } 
    break; 
default: 
    $value = $product->getData($attribute_code); 
    break; 
} 

$attributesRow[] = $value; 

如果有人能改善這個(使其更簡單/更有效),請張貼一個答案。

+2

看看這篇文章http://blog.chapagain.com.np/magento-how-to-get-attribute-name-and-價值/ –

+1

謝謝,有用的文章。 – Jamie

回答

11

對於下拉菜單和多重選擇,只有產品(這不是一般的EAV技巧),您可以使用getAttributeText()

$value = $product->getAttributeText($attribute_code); 
+0

謝謝你指出。我想知道這種方法是如何處理某些屬性的,而不是其他的。 – Jamie

0

這取決於你如何設置屬性(它與你想達到它的上下文訪問?),但最簡單的方法通常是這樣的(對於meta_title爲例):

$product->getMetaTitle() 
+0

謝謝,但某些屬性可能無法使用魔術吸氣劑方法訪問。 – Jamie

3

在1.7版本中,$product->getAttributeText($attribute_code)工作不適合我的產品頁面上。起初我以爲這是因爲該屬性不在catalog_product_flat索引中。但事實證明,該屬性在那裏。無論如何,下面的代碼適用於我。我嘗試簡單的代碼,然後回到EAV代碼上。

所以我用這樣的代碼:

$value = $product->getAttributeText($attribute_code); // first try the flat table? 
if(empty($value)) { // use the EAV tables only if the flat table doesn't work 
    $value = $product->getResource()->getAttribute($attribute_code)->getFrontend()->getValue($product); 
} 
+1

我正在檢索一個產品集合,並且'getValue($ product)'返回''No''。我將'$ product'改成了'Mage :: getModel('catalog/product') - > load($ product-> getEntityId())',並得到了一個產品,其方法將轉到數據庫。否則,代碼將嘗試從其內部數組值中獲取數據。在正常情況下,我期望上面的代碼工作得很好。 – pavlindrom

相關問題