如何在自定义集合上使用addFieldToFilter

时间:2013-11-16 00:19:36

标签: php magento custom-backend

我想知道是否可以在 Magento 1.7.2中过滤自定义集合。 我目前的代码如下:

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

我可以打印它生成的查询,如果我在MySQL中运行它,我会得到正确的表行。但是,返回的集合中没有项目。没有过滤器的集合也会返回所有正确的项目,因此集合实现没有问题。集合类继承自Mage_Core_Model_Resource_Db_Collection_Abstract

查询:

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

当前丑陋的解决方法:

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

3 个答案:

答案 0 :(得分:1)

我不是百分百确定,但你需要这个: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

希望它有所帮助, 干杯

答案 1 :(得分:1)

我可能因过度依赖xDebug而搞砸了。显然,这个集合正在被addFieldToFilter()方法过滤,我没有得到任何项目的原因是因为Magento的延迟加载。我只需要使用$ collection,它只会在那时查询项目。

答案 2 :(得分:0)

我还要补充一点,在调用create()方法之前,您可能需要从工厂类中调用getCollection()方法并调用addFieldToFilter()方法。