2016-05-01 84 views
1

我有一个自定义集合,我希望通过创建日期和Het条目筛选产生“昨天”Magento的过滤器收集的创建时间(今天,昨天,周,小时等)

集合条目

//dates are set in controller using 
setCreatedTime(Mage::getModel('core/date')->gmtDate()); 

创建昨天(不工作)

//3 products items Yesterday 
//below filtering outputs incorrect entries 
$collection = Mage::getModel('things/things')->getCollection(); 

我试过了,但输出不正确的条目;

//thought strtotime('yesterday') would work.. 
$collection->addFieldToFilter('created_time', array('gt' => Mage::getModel('core/date')->date('Y-m-d H:i:s', strtotime('yesterday')))); 
$collection->addFieldToFilter('created_time', array('gt' => Mage::getModel('core/date')->date('Y-m-d H:i:s', strtotime('-1 day')))); 
$collection->addFieldToFilter('created_time', array('from'=> strtotime('-1 day', time()),'to'=> time(),'datetime' => true)); 
$fromDate = date('Y-m-d H:i:s', strtotime($fromDate)); 
$toDate = date('Y-m-d H:i:s', strtotime($toDate)); 
$collection->addFieldToFilter('created_time', array('from'=>$fromDate, 'to'=>$toDate)); 

造就了今天(当天)(作品)

//5 products items today with timestamp 2016-05-01 05:22:53 
//below filtering outputs correct entries 
$collection = Mage::getModel('things/things')->getCollection(); 
$collection->addFieldToFilter('created_time', array('gt' => Mage::getModel('core/date')->date('Y-m-d H:i:s', strtotime('today')))); 

创过去一周(作品)

//23 products items with timestamps for this week 
//below filtering outputs correct entries 
$collection = Mage::getModel('things/things')->getCollection(); 
$collection->addFieldToFilter('created_time', array('gt' => Mage::getModel('core/date')->date('Y-m-d H:i:s', strtotime('-1 week')))); 

回答

1

试试吧addFieldToFilter更改为addAttributeToFilter。下面的方法通常是我如何对集合进行日期过滤。注意date属性被设置为true。

$collection = Mage::getModel('things/things')->getCollection(); 
$collection->addAttributeToFilter('created_time', array(
     'from' => $fromDate, 
     'to' => $toDate, 
     'date' => true, 
     )); 

你也可以看到,查询被执行以下

echo $collection->getSelect()->__toString(); 
+0

Thanks @Ash for your input – BENN1TH

1

添加到@Ash答案调试产生的,见下文如何;

我过去一小时

$things = Mage::getModel('things/things')->getCollection(); 
$things->addFieldToFilter('things_type', 'view'); 
$fromDate = date('Y-m-d H:i:s', strtotime('-1 hour')); 
$toDate = date('Y-m-d H:i:s', strtotime(now())); 
$things->addFieldToFilter('created_time', array(
    'from' => $fromDate, 
    'to' => $toDate, 
    'date' => true, 
    )); 
return count($things); 

中创建条目,我得到了昨天创建的条目;

$now = Mage::getModel('core/date')->timestamp(time()); 
$dateStart = date('Y-m-d' . ' 00:00:00', $now); 
$dateEnd = date('Y-m-d' . ' 23:59:59', $now); 
$things = Mage::getModel('things/things')->getCollection(); 
$things->addFieldToFilter('things_type', 'view'); 
$things->addFieldToFilter('created_time', array('from' => $dateStart, 'to' => $dateEnd)); 
return count($things);