4

我很难在带有自定义表的集合上设置日期过滤器。已经在这里这里以及其他一些地方搜索过,但仍然无法得到我需要的东西。问题是我无法将NULL值添加到结果集中。

到目前为止,经过多次反复试验,我当前的代码:

$myBannersCollection = Mage::getModel('banners/bannersadmin')->getCollection()
                   ->addfieldtofilter('banner_prod_id',$currentProdID)
                   ->addfieldtofilter('banner_start_date', 
                       array(
                         array('from' => Mage::getModel('core/date')->gmtDate()),
                                 'banner_start_date' => null))
                   ->addfieldtofilter('banner_end_date',
                       array(
                         array('gteq' => Mage::getModel('core/date')->gmtDate()),
                                 'null' => true)
                                  );
var_dump((string) $myBannersCollection->getselect());

此代码输出以下 sql 片段:

SELECT `main_table`.* 
  FROM `dts_banners_admin` AS `main_table` 
 WHERE (banner_prod_id = '16')
  AND (((banner_start_date >= '2012-11-28 14:39:13') OR (banner_start_date='')))
   AND (banner_end_date IS NULL)

尝试了几种不同的选项来添加NULL条件,但我无法得到类似的东西:

SELECT `main_table`.* 
  FROM `dts_banners_admin` AS `main_table` 
 WHERE (banner_prod_id = '16')
  AND (((banner_start_date>='2012-11-28 14:39:13') OR (banner_start_date IS NULL)))
   AND ((banner_end_date >= '2012-11-28 14:39:13') OR (banner_end_date IS NULL))

PS:Magento 上有BETWEEN运营商addfieldtofilter吗?

4

1 回答 1

13

知道了!感谢这个SO answer。需要为IS NULL子句添加另一个数组。现在代码是:

$myBannersCollection = Mage::getModel('banners/bannersadmin')->getCollection()
                   ->addfieldtofilter('banner_prod_id',$currentProdID)
                   ->addfieldtofilter('banner_start_date', 
                        array(
                         array('to' => Mage::getModel('core/date')->gmtDate()),
                                 array('banner_start_date', 'null'=>'')))
                   ->addfieldtofilter('banner_end_date',
                        array(
                         array('gteq' => Mage::getModel('core/date')->gmtDate()),
                             array('banner_end_date', 'null'=>''))
                                  );

并输出:

SELECT `main_table`.*
  FROM `dts_banners_admin` AS `main_table`
 WHERE (banner_prod_id = '16')
 AND (((banner_start_date>='2012-11-28 15:12:03') OR (banner_start_date IS NULL)))
   AND (((banner_end_date >= '2012-11-28 15:12:03') OR (banner_end_date IS NULL)))

编辑

修改了banner_start_date我使用from而不是to的时间,因此错误地确定了期间并且没有返回任何数据。

于 2012-11-28T15:15:00.973 回答