2016-05-01 95 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); 
相關問題