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


How to use addFieldToFilter on a custom collection

我想知道是否可以在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()){
           ...
        }
   }

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

希望对您有所帮助,干杯

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

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

相关文章:
  • 没有找到相关文章