Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Attribute model by attribute_code in Magento

Tags:

magento

How could I get Attribute model (from: eav_attribute table) by attribute_code in Magento?
Notice:
- I don't care what is entity_type.
Thank you so much.

like image 886
vietean Avatar asked Sep 26 '11 07:09

vietean


People also ask

How do I get attribute code in Magento 2?

Just instantiate the Magento\Eav\Api\AttributeRepositoryInterface class to retrieve the id value. Here, We are fetching Product SKU attribute Id programmatically. You can pass any attribute value you want to retrieve with the entity type. $getId = $this->getAttributeId();

How do I get attribute code?

You can use anywhere this code by inject \Magento\Eav\Model\Entity\Attribute class in your construct. After that, you can call getCustomAttributeCode() function to get attribute code.


2 Answers

You have to know entity_type because you can have the same attribute_code for different entities. So to get attribute model:

$attributeModel = Mage::getModel('eav/entity_attribute')->loadByCode($entity_type, $attributeCode);

$entity_type parameter can be numeric (id directly), string (for example 'catalog_product' or Mage_Catalog_Model_Product::ENTITY) or it can be instance of model Mage_Eav_Model_Entity_Type

like image 147
azakolyukin Avatar answered Oct 05 '22 08:10

azakolyukin


Perhaps you can read the attributes by filter the collection

   Mage::getModel('eav/entity_attribute')->getCollection()->addFieldToFilter('attribute_code', array('in' => $codes) )

Since I need the attributes from the Product by code, I do it like this:

    $codes = (array) $codes; 
    $res = array_intersect_key($this->getAttributes(), array_flip($codes));

$codes is an attribute_code-array Scope: extended Mage_Catalog_Model_Product

like image 3
Andreas Dyballa Avatar answered Oct 05 '22 08:10

Andreas Dyballa