【问题标题】:Is there a simpler way to get an attribute's frontend value?有没有更简单的方法来获取属性的前端值?
【发布时间】:2011-08-18 10:46:12
【问题描述】:

我有一个属性代码数组,我需要获取以下值:

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

遍历产品集合后,我得到属性的前端值,如下所示:

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

仅使用$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;

如果有人可以改进这一点(使其更简单/更高效),请发布答案。

【问题讨论】:

标签: magento attributes magento-1.5


【解决方案1】:

对于下拉菜单和多选,并且仅适用于产品(这不是一般的 EAV 技巧),您可以使用 getAttributeText()

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

【讨论】:

  • 感谢您指出这一点。我想知道该方法是如何对某些属性起作用而对其他属性不起作用的。
【解决方案2】:

在 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);
}

【讨论】:

  • 我正在检索产品集合,并且执行getValue($product) 正在返回'No'。我将$product 更改为Mage::getModel('catalog/product')->load($product->getEntityId()) 并得到了一个产品,其方法将进入数据库。否则,代码将尝试从其内部值数组中获取数据。在正常情况下,我希望上面的代码可以正常工作。
【解决方案3】:

这取决于您如何设置属性(是否可以从您尝试访问的上下文中访问它?),但最简单的方法通常是这样的(例如,对于 meta_title):

$product->getMetaTitle()

【讨论】:

  • 谢谢,但使用魔术 getter 方法可能无法访问某些属性。
猜你喜欢
  • 2020-03-19
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 2011-01-07
  • 2020-10-26
相关资源
最近更新 更多