2011-08-18 29 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

相关问题