Changing The Select After The Collection Has Been Loaded

Posted on August 4, 2011 by admin There have been 0 comments

Lets observe at the following example:

For some reason you want to show the products whose price is lower than 100$.
If you go to list.phtml at app/design/frontend/base/default/template/catalog/product, you will see the following line:

$_productCollection=$this->getLoadedProductCollection();

$_productCollection is instance of Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection, and of course this is already loaded collection (collection that has items). resource collections in Magento - once the collection is loaded, you cannot add anything to the "select" and then call "load" again - this will not change the items of a collection. The solution is:

$_productCollection->clear();
$_productCollection->getSelect()->where('price_index.price < 100'); $_productCollection->load();

In line 1 we called to "clear" function that deleted all items in the collection, but preserved the current select. So in the line 2 we added stuff to the select, and called "load". This gave us the desired result.


This post was posted in Working With Magento Collections and was tagged with Magento collections

Comments
Magento is a well-engineered eCommerce platform designed to help engineers develop customized eCommerce online stores. Due to lack of proper coding documentation, Engineer-ing.com was created with the sole purpose of instructing Magento developers to-be with the "how-to-do" know-how. In the event of unresolved issues, you are more than welcome to contact me for consultation. However, please do so only if you possess a Software Engineering background and you're able to specify your question.