Magento,按日期过滤器收集并包含空值

时间:2012-11-28 14:55:46

标签: magento magento-1.7

我很难用自定义表格在集合上设置日期过滤器。已搜索过herehere以及其他一些地方,但仍无法获得我需要的内容。问题是我无法将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运算符吗?

1 个答案:

答案 0 :(得分:12)

知道了!感谢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,因为我使用而非转换为,因此错误地确定了句点并且没有返回任何数据。