如何检查产品属性集中是否存在属性? Magento的

时间:2013-01-19 12:09:20

标签: magento attributes product catalog

如何检查产品属性集中是否存在属性?

我需要知道产品是否具有其属性集的属性。

我得到了属性:

$attrPricekg = Mage::getModel('catalog/product')->load($_product->getId())->getPricekg();

如果产品属性集中存在属性,则$ attrPricekg显示:产品的设置值 如果没有为产品设置值,则为0。

如果产品属性集中不存在该属性,则$ attrPricekg显示0.这是我的问题..我需要避免这种情况,我想检查该产品的属性是否存在。

感谢。

4 个答案:

答案 0 :(得分:28)

现在我会提供一个无论如何都有效的答案!

$product = Mage::getModel('catalog/product')->load(16);

$eavConfig = Mage::getModel('eav/config');
/* @var $eavConfig Mage_Eav_Model_Config */

$attributes = $eavConfig->getEntityAttributeCodes(
    Mage_Catalog_Model_Product::ENTITY,
    $product
);

if (in_array('pricekg',$attributes)) {
    // your logic
}

答案 1 :(得分:6)

要检查产品中是否存在特定属性,即使该属性的值为“null”,它也应返回true。

一种有效的方法是:

$attr = Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product',$code);
if (null!==$attr->getId())

{         //属性在这里存在代码     }

它当然也可以写成一行:

if(null!===Mage::getModel('catalog/resource_eav_attribute')->loadByCode('catalog_product','attributecode_to_look_for')->getId()) {
    //'attributecode_to_look_for' exists code here
}

找到它并修改了一下: https://github.com/astorm/Pulsestorm/issues/3

答案 2 :(得分:0)

可能这种方式对你更好:

$attribute = Mage::getModel('catalog/product')->load($productId)->getResource()->getAttribute($attributeCode);
if ($attribute && $attribute->getId()) { ... }

你也可以试试

$attributes = $product->getAttributes();

但您可以检查所有属性集合:

$entityTypeId = Mage::getModel('eav/entity')
            ->setType('catalog_product')
            ->getTypeId();
$attributeId = 5;
$attributeSetName   = 'Default';
$attributeSetId     = Mage::getModel('eav/entity_attribute')
                ->getCollection()
                ->addFieldToFilter('entity_type_id', $entityTypeId)
                ->addFieldToFilter('attribute_set_name', $attributeSetName)
                ->addFieldToFilter('attribute_id', $attributeId)
                ->getFirstItem();

可能是源代码需要一些更正,但我认为你会理解这个想法。

在此处查看更多示例,还有 - http://www.blog.magepsycho.com/playing-with-attribute-set-in-magento/

答案 3 :(得分:-3)

编辑:这不是正确答案。

$product->offsetExists('pricekg');

请参阅Varien_Object::offsetExists() (link)

相关问题