Skip to content

Instantly share code, notes, and snippets.

@michaelhoang
Last active August 29, 2015 14:19
Show Gist options
  • Save michaelhoang/11201dd5e7e4fb922d3d to your computer and use it in GitHub Desktop.
Save michaelhoang/11201dd5e7e4fb922d3d to your computer and use it in GitHub Desktop.
All about attributes
// Get attribute object by code
Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'color');
// Get entity type object by code
Mage::getModel('eav/entity_type')->loadByCode('catalog_product');
// ===========================================================
public function joinEavTablesIntoCollection($collection, $mainTableForeignKey, $eavType)
{
$entityType = Mage::getModel('eav/entity_type')->loadByCode($eavType);
$attributes = $entityType->getAttributeCollection();
$entityTable = $collection->getTable($entityType->getEntityTable()); //$entityTable = customer_entity
//Use an incremented index to make sure all of the aliases for the eav attribute tables are unique.
$index = 1;
foreach ($attributes->getItems() as $attribute) {
$alias = 'table' . $index;
if ($attribute->getBackendType() != 'static') {
$table = $entityTable . '_' . $attribute->getBackendType(); // int || varchar || text
$field = $alias . '.value';
$collection->getSelect()
->joinLeft(array($alias => $table),
'main_table.' . $mainTableForeignKey . ' = ' . $alias . '.entity_id and ' . $alias . '.attribute_id = ' . $attribute->getAttributeId(),
array($attribute->getAttributeCode() => $field)
);
}
$index++;
}
//Join in all of the static attributes by joining the base entity table.
$collection->getSelect()->joinLeft($entityTable, 'main_table.' . $mainTableForeignKey . ' = ' . $entityTable . '.entity_id');
return $collection;
}
// Call
$wishlistCollection = Mage::getModel('wishlist/wishlist')->getCollection();
$wishlistCollection = Mage::helper('awesome')->joinEavTablesIntoCollection($wishlistCollection, 'customer_id', 'customer');
echo $wishlistCollection->getSelect()->__toString();
// ============================================
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment