magento-1.9,eav,flat,join-table – How to Join EAV to Flat Table and Update EAV in Magento 1.9

eavflatjoin-tablemagento-1.9

This will be two parts

1.) Join an EAV to a Flat Table the Magento way

2.) Import into Flat Table that will update the EAV Table.

Basically be able to Export(Flat Table) and Import(with flat table) but be able to extend the data into the EAV during import.

Best Answer

We can join eav table to flat table. Below is the example for joining the wishlist table to the customer's eav tables:

$wishlistCollection = Mage::getModel('wishlist/wishlist')->getCollection();
$wishlistCollection = Mage::helper('abc')->joinEavTablesIntoCollection($wishlistCollection, 'customer_id', 'customer');

echo $wishlistCollection->getSelect()->__toString();

After that in your helper file i.e "abc" create the below function:

public function joinEavTablesIntoCollection($collection, $mainTableForeignKey, $eavType){

   $entityType = Mage::getModel('eav/entity_type')->loadByCode($eavType);
   $attributes = $entityType->getAttributeCollection();
   $entityTable = $collection->getTable($entityType->getEntityTable());

   $index = 1;

   foreach ($attributes->getItems() as $attribute){
      $alias = 'table'.$index;
      if ($attribute->getBackendType() != 'static'){
         $table = $entityTable. '_'.$attribute->getBackendType();
         $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++;
    }

   $collection>getSelect()>joinLeft($entityTable,'main_table.'.$mainTableForeignKey.' = '.$entityTable.'.entity_id');

   return $collection;
}

This is the answer to the first part of your question.

Related Topic