0

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

3 回答 3

1

我不是 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

希望有帮助,加油

于 2013-11-16T13:09:34.393 回答
1

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

于 2013-11-18T21:21:29.950 回答
0

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

于 2018-07-31T11:49:59.497 回答