Last active
August 29, 2015 14:15
-
-
Save lethak/9edc56d75712b87d0f77 to your computer and use it in GitHub Desktop.
Adding seconds to a DateTime object in doctrine2 DQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// in symfony2 app/ config.yml ... | |
doctrine: | |
orm: | |
entity_managers: | |
default: | |
dql: | |
datetime_functions: | |
unix_timestamp: Acme\AcmeBundle\DoctrineExtension\ORM\Query\AST\Functions\UnixTimestamp | |
// THEN, In a custom doctrine function file | |
//... SiteBundle\DoctrineExtension\ORM\Query\AST\Functions\UnixTimestamp.php | |
namespace Acme\AcmeBundle\DoctrineExtension\ORM\Query\AST\Functions; | |
use Doctrine\ORM\Query\Lexer; | |
use Doctrine\ORM\Query\SqlWalker; | |
use Doctrine\ORM\Query\Parser; | |
/** | |
* UnixTimestampFunction ::= "UNIXTIMESTAMP" "(" ArithmeticPrimary ")" | |
*/ | |
class UnixTimestamp extends \Doctrine\ORM\Query\AST\Functions\FunctionNode | |
{ | |
public $firstDateExpression = null; | |
public function parse(Parser $parser) | |
{ | |
$parser->match(Lexer::T_IDENTIFIER); // (2) | |
$parser->match(Lexer::T_OPEN_PARENTHESIS); // (3) | |
$this->firstDateExpression = $parser->ArithmeticPrimary(); // (4) | |
$parser->match(Lexer::T_CLOSE_PARENTHESIS); // (3) | |
} | |
public function getSql(SqlWalker $sqlWalker) | |
{ | |
return 'UNIX_TIMESTAMP(' . | |
$this->firstDateExpression->dispatch($sqlWalker). | |
')'; // (7) | |
} | |
} | |
/// THEN, In your controller/Repository.. | |
$now = new \DateTime("now",new \DateTimeZone('UTC')); | |
$QB = $this->createQueryBuilder('h'); | |
$Query = $QB->where('h.dateLastCrawled IS NULL') | |
->orWhere($QB->expr()->sum( "UNIX_TIMESTAMP(h.dateLastCrawled)", 'h.revisitAfterSeconds')." <= UNIX_TIMESTAMP(:now)") | |
->setParameter(':now', $now) | |
->orderBy('h.revisitAfterSeconds', 'ASC') | |
->setFirstResult($batchOptions['offset']) | |
->setMaxResults($batchOptions['limit']) | |
->getQuery() | |
; | |
$result = $Query->getResult(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated the gist with a WORKING SOLUTION