Doctrine 2 DATE_ADD mysql function with computed interval value

doctrine-orm, mysql, sql-date-functions

Solution

By default Doctrine does not support all the functions of a specific vendor, such as the `DATE_ADD`. However, you can use custom defined functions. That link has an example specifically for date add.

Extending DQL in Doctrine 2: User-Defined Functions

The other option, depending on the complexity of the query, is just to handle this in the application code. if your `mydatetimefield` is actually a datetime, Doctrine will convert that to a php `DateTime` in the returned object.

$myDateTimeField = $object->getMyDateTimeField();
$myDateTimeField->add(new DateInterval( $object->getMyField1() + $object->getMyField2() . 'M'));

Lastly, you could always use `dbal` as well.

Problem

I have a query that gives me a unix timestamp calculated selecting the datetime value of a table field and then adding another value of the table. The query is something like the following: ``` SELECT UNIX_TIMESTAMP(DATE_ADD(mydatetimefield, INTERVAL m.myfield1 + m.myfield2 MINUTE)) FROM mytable AS m ``` this query executes correctly from phpMyAdmin but when I try to use it with the createQueryBuilder method of Doctrine 2 I get an error at "myfield". It seems that it doesn't support a computed value after the INTERVAL keyword ``` Error: Expected Doctrine\ORM\Query\Lexer::T_COMMA, got 'm' ``` how can I then get the same query result by using doctrine? I use the querybuilder because I have some named parameters

Original source