簡體   English   中英

Doctrine Mongodb ODM和DateTime查詢

[英]Doctrine Mongodb ODM and DateTime query

我可以在這個問題上使用一些幫助。 我正在使用Symfony2 + mongodb + doctrine創建一個應用程序。 我只想使用Doctrine ODM查詢過去5分鍾內登錄過的所有用戶。 我有一個User集合,其中包含一個名為date_last_login的日期字段。

所以我嘗試使用這樣的querybuilder:

<?php
// Creating a DateTime object and susbtract 5 min from now
// local time is 15:40:05, timezone: 'Europe/Paris'
$_dateTime = new \DateTime();
$_interval5Min = new \DateInterval('PT5M');
$_dateTime->sub($_interval5Min);

$query = $this->createQueryBuilder('User')
                ->field('date_last_login')->gte($_dateTime)
                ->getQuery();
                ->execute();

當我使用symfony2 profiler查看匯編的查詢時,我得到的是:

db.User.find({ "date_last_login": { "$gte": new Date("Fri, 23 Dec 2011 15:30:05 +0100") } });

看起來很好,除了日期提前10分鍾而不是5分鍾? 我只是不明白。 如果我轉儲我的php DateTime對象,日期是正確的:2011-12-23 15:35:05(15:40之前的五分鍾)。

所以我嘗試組裝相同的查詢而不減少任何分鍾,這一次,一切都很好:

<?php
// local time is 15:50:00
$query = $this->createQueryBuilder('User')
            ->field('date_last_login')->gte(new \DateTime())
            ->getQuery();
            ->execute();

// query is ok:
db.User.find({ "date_last_login": { "$gte": new Date("Fri, 23 Dec 2011 15:50:00 +0100") } });

我究竟做錯了什么 ? 謝謝您的幫助!

要在date_last_login大於5 minutes時為get數據創建查詢構建器,有3種方法

1)使用您的日期時間格式創建DateTime對象,並從DateTime對象獲取timestamp ,然后創建MongoDate對象:

$timeBefore5MinutesAgo  = new \DateTime(date('Y-m-d H:i:s',\time() - 5 * 60));
$mongoDateBefore5MinutesAgo = new \MongoDate($currentDateWithTime->getTimestamp());

$query = $this->createQueryBuilder('User')
    ->field('date_last_login')->gte($mongoDateBefore5MinutesAgo)
    ->getQuery();
    ->execute();

2)創建MongoDate對象並使用strtotime將日期timestamp格式轉換為timestamp

$mongoDateBefore5MinutesAgo = new \MongoDate(strtotime(date('Y-m-d H:i:s',\time() - 5 * 60)));

$query = $this->createQueryBuilder('User')
    ->field('date_last_login')->gte($mongoDateBefore5MinutesAgo)
    ->getQuery();
    ->execute();

3)僅在Doctrine 2 ODM情況下,您可以使用日期時間格式創建DateTime對象:

$timeBefore5MinutesAgo  = new \DateTime(date('Y-m-d H:i:s',\time() - 5 * 60));

$query = $this->createQueryBuilder('User')
              ->field('date_last_login')->gte($timeBefore5MinutesAgo)
              ->getQuery();
              ->execute();

所有3種方法都會創建查詢:

db.User.find({ "date_last_login": { "$gte": new ISODate("2014-03-15T19:35:08+02:00") } });

這可能是由於這個PHP bug在5.3.3中修復了:

https://bugs.php.net/bug.php?id=50916

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM