Question

I was wondering if it's possible to filter a custom collection in Magento 1.7.2. My current code looks like this:

$collection = $model->getCollection()
   ->addFieldToFilter('gc_id',array('gt' => 0))
   ->addFieldToFilter('expiration_date', array('lteq' => Mage::getModel('core/date')->gmtDate()));

I can print the query it generates and if I run it in MySQL I do get the right table rows. However, the collection that gets returned has no items in it. The collection without the filters also returns all the right items, so there are no issues with collection implementation. The collection class inherits from Mage_Core_Model_Resource_Db_Collection_Abstract

Query:

SELECT `main_table`.* FROM `st_freegiftcard` AS `main_table` WHERE (gc_id > 0) AND (expiration_date <= '2013-11-15 23:59:20')

Current ugly workaround:

  foreach($collection as $free_gc){
        if($free_gc->getGcId() > 0 
             && $free_gc->getExpirationDate() <= Mage::getModel('core/date')->gmtDate()){
           ...
        }
   }
Was it helpful?

Solution 2

I may have screwed up by relying on the xDebug too heavily. Apparently the collection is being filtered by the addFieldToFilter() method, the reason why I was not getting any items to show up was because of Magento's lazy loading. I just had to use the $collection and it would query the items only at that point.

OTHER TIPS

I am not 100% sure but you need this: addAttributeToFilter

- addAttributeToSelect: To add an attribute to entities in a
   collection, * can be used as a wildcard to add all available
   attributes
 - addFieldToFilter: To add an attribute filter to a collection, this
   function is used on regular, non-EAV models
 - addAttributeToFilter: This method is used to filter a collection of
   EAV entities
 - addAttributeToSort: This method is used to add an attribute to sort
   order

Hope it helps, Cheers

Let me also add that you may need to call the create() method from the factory class and the call the getCollection() method before calling the addFieldToFilter() method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top