I'm having a difficult time settling up a dates filter on a collection with custom tables. Have searched here and here and some other places but still can not get what I need. The problem is that I can't add the NULL
values to the result set.
So far my current code after several trial and error tests:
$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());
This code ouputs the following sql snippet:
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)
Have tried several different options to add the NULL
condition but no way I can get something like:
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: does Magento has a BETWEEN
operator on the addfieldtofilter
?
Got it! Thanks to this SO answer. Needed to add another array just for the IS NULL
clause. Now the code is:
$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'=>''))
);
And outputs this:
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)))
EDIT
Modified the banner_start_date
as I was using from instead of to and so the period was incorrectly settled up and no data was returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With