按创建时间(今天,昨天,周,小时等)收集Magento过滤器

时间:2016-05-01 02:19:24

标签: date magento collections filter

我有一个自定义集合,我希望按创建日期过滤,并创建het条目"昨天"

收集条目

//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'))));

2 个答案:

答案 0 :(得分:1)

尝试将addFieldToFilter更改为addAttributeToFilter。以下方法通常是我对集合进行日期过滤的方法。请注意,date属性设置为true。

div

您还可以通过执行以下操作来查看为调试生成的查询

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

答案 1 :(得分: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);