如何获取属性集名称?

31

我想在Magento产品视图模板中获取属性集名称。我可以通过$_product->getAttributeText('attribute')获取属性值,但我该如何获取属性集名称?

我希望只有当某个属性属于特定的属性集时才显示它。

5个回答

74
无论什么时候您拥有一个产品对象,您都可以像这样访问其属性集:
$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($product->getAttributeSetId());
$attributeSetName  = $attributeSetModel->getAttributeSetName();
这将给你属性集的名称,然后你可以使用strcmp进行比较:
if(0 == strcmp($attributeSetName, 'My Attribute Set')) {
    print $product->getAttributeText('attribute');
}

一位匿名用户提出了一个编辑建议,将$attributeSet更正为#attributeSetName。看起来很合理,所以我批准了它。但是,我不熟悉这种语言,请检查一下它是否正确。 - user616736
最后一行应该是:$attributeSetName = $attributeSetModel->getAttributeSetName();,末尾不要加上 ')'。 - Yeroon
奇怪的选择strcmp函数?为什么不使用直接比较===? - Matthew Haworth
@MatthewHaworth 说实话,这个答案已经是半个十年前的事了(天啊...),所以我真的不知道为什么。如果我必须猜测的话,我可能更喜欢使用strcmp,因为它仍然允许将其他数据类型隐式转换为字符串,但比“==”更严格。在这种特定情况下,它们都可以很好地工作。 - Joe Mastey

26

如果想要更简洁的代码,可以将其缩短为:

$attributeSetName = Mage::getModel('eav/entity_attribute_set')->load($_product->getAttributeSetId())->getAttributeSetName();

14

请尝试以下代码:

$entityTypeId = Mage::getModel('eav/entity')
                ->setType('catalog_product')
                ->getTypeId();
$attributeSetName   = 'Default';
$attributeSetId     = Mage::getModel('eav/entity_attribute_set')
                    ->getCollection()
                    ->setEntityTypeFilter($entityTypeId)
                    ->addFieldToFilter('attribute_set_name', $attributeSetName)
                    ->getFirstItem()
                    ->getAttributeSetId();
echo $attributeSetId;

以下文章中,了解更多关于Magento属性集的信息。

谢谢


1

Joe的答案需要进行一些修改才能正常工作。

首先应该是$_product而不是$product,其次在最后一行有一个错误的')'。

以下代码应该是正确的:

$attributeSetModel = Mage::getModel("eav/entity_attribute_set");
$attributeSetModel->load($_product->getAttributeSetId());
$attributeSetName = $attributeSetModel->getAttributeSetName();

0

如果用户决定稍后更改文本,与文本值进行比较可能会出现问题 - 在Magento中更改属性集很容易。另一个选项是使用永远不会更改的基础ID。

您可以通过查找数据库中attribute_set_id列的值来获得此值

select * from eav_attribute_set;

这个数字也在下面加粗的管理编辑链接中

http://.../index.php/admin/catalog_product_set/edit/id/10/key/6fe89fe2221cf2f80b82ac2ae457909ce04c92c51716b3e474ecad672a2ae2f3/

你的代码将简单地使用该产品的属性。基于上面链接中的id为10,这将是:

if (10 == $_product->getAttributeSetId()) {
  //Do work
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接