Expression mysql NOW() in Doctrine QueryBuilder
Asked Answered
B

2

31

How to use the expression mysql NOW() in doctrine querybuilder?

Bearable answered 16/12, 2012 at 21:48 Comment(0)
F
53

In Doctrine2 you have to use one of the following instead of NOW().
This:

CURRENT_TIMESTAMP()

Or:

...
createQuery(...'WHERE x.date = :now')
->setParameter('now', new \DateTime('now'))
...

If you want only time or only date use one of those: CURRENT_TIME() and CURRENT_DATE()

Documentation can be found here.

Flesh answered 17/12, 2012 at 1:24 Comment(3)
Documentation link reports not found, please update.Coverlet
This CURRENT_TIMESTAMP() thing has never has worked for me. Could you provide an example of how that is used? I don't wan't to use the web server's time, rather the database. I always end up writing raw SQL (still binding params) and forgoing the query builder.Gerous
Also notice 'now' is default param for DateTime, so new \DateTime() is enough.Earflap
C
9

Using query builder it would look like this:

$qb
    ->select('B')
    ->from('RandomBundle:Banana', 'B')
    ->where(
        $qb->expr()->gt('B.expiresAt', ':now')
    )
    ->setParameter('now', '\'CURRENT_TIMESTAMP()\'');

Note: extra quotes on parameter set is required to get CURRENT_TIMESTAMP() function working.

Or simply

$qb
    ->select('B')
    ->from('RandomBundle:Banana', 'B')
    ->where(
        $qb->expr()->gt('B.expiresAt', 'CURRENT_TIMESTAMP()')
    );
Customary answered 19/10, 2015 at 12:8 Comment(2)
In the second example, you can use the shorter B.expiresAt > CURRENT_TIMESTAMP() comparison directly inside the where call instead of using a query builder expressionBarbur
I assume it was desired to use database's time, not some frontend web server's. Alternate options are to use a resultset mapper/native query, or to extend Doctrine and write your own Doctrine\ORM\Query\AST\Functions.Gerous

© 2022 - 2024 — McMap. All rights reserved.