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

7

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

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

使用以下代码获取属性:

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

如果产品属性集中存在属性,则 $attrPricekg 会显示:为该产品设置值,或者如果没有设置任何值,则显示 0。
如果产品属性集中不存在属性,则 $attrPricekg 显示 0。这是我的问题...我需要避免这种情况,我想检查该产品是否不存在该属性。
谢谢。
4个回答

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
}

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


这是一个通用的、完美的解决方案。如果要删除某个属性,只需检查其是否存在,然后使用 $installer->removeAttribute('catalog_product', 'attributecode_to_look_for'); 即可。 - R T
谢谢你的回答。在第一个示例的条件中添加一个闭合括号后,它可以工作了! - Zsolti

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/


第一种解决方案不正确。我需要检查特定的产品。 - user1992779
尝试执行 $attribute = Mage::getModel('catalog/product')->load(1)->getResource()->getAttribute($attributeCode); - freento
尝试一下: $attributes = $product->getAttributes(); - freento
谢谢。 :) $attributes = $product->getAttributes() 和 foreach 结构帮了我大忙!!! - user1992779

-4

这个条件只有在属性有值的情况下才会返回true吗?还是当product_entity_attribute_[type]表中没有记录时,Magento会在$_data中放入一个键为NULL值的项? - beeplogic
有人,请删除这个回答! - undefined

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