2013-01-19 47 views
5

如何檢查產品屬性集中是否存在屬性?如何檢查產品屬性集中是否存在屬性? Magento

我需要知道某個產品是否具有其屬性集的屬性。

我得到的屬性:

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

如果在設置產品屬性存在attribut,$ attrPricekg顯示:該產品 或0,如果沒有價值,爲產品設定的設定值。

如果產品屬性集中不存在該屬性,$ attrPricekg顯示0.這是我的問題。我需要避免這種情況,我想檢查該產品的屬性不存在。

謝謝。

回答

-3

編輯:這是不正確的答案。

$product->offsetExists('pricekg'); 

Varien_Object::offsetExists() (link)

+0

如果這個屬性有值,這隻會返回true嗎?或者,當product_entity_attribute_ [type]表中沒有記錄時,magento是否將具有NULL值的$ _data中的鍵放入? – beeplogic

+7

這不是正確的答案。 – benmarks

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/

+0

第一種解決方案無法正常工作。我需要檢查特定的產品。 – user1992779

+0

嘗試做$ attribute = Mage :: getModel('catalog/product') - > load(1) - > getResource() - > getAttribute($ attributeCode); – freento

+0

也可以嘗試 $ attributes = $ product-> getAttributes(); – freento

26

現在我會提供一個適用的答案!

$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 
} 
5

要檢查產品中是否存在特定屬性,即使該屬性的值爲'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

+0

這是一個總體和完整的。我需要這個刪除屬性,只有當它存在。刪除現有的attrib'$ installer-> removeAttribute('catalog_product','attributecode_to_look_for');'簡單。 –

+0

感謝您的回答。在第一個示例的條件中添加了右括號後,它就可以工作了! – Zsolti