I want to get the items which were created today with by a QueryBuilder from Doctrine2. I want to compare the createdAt(Datetime) field with today parameter(Date). Is it possible to do that in one query?
$qb = $this->createQueryBuilder('i');
$qb->innerJoin('i.type', 'it');
$qb->andWhere('it.name = :type');
$qb->andWhere('i.createdAt < :today');
// i.createdAt == datetime and :today parameter is a date
It's rare that such a mature ORM does not provide the
DATE
function. However, to get a date out of a datetime field, you can apply theSUBSTRING
function like this:Hope it helps!
It is also possible to use built-in function
DATE_DIFF(date1, date2)
which returns difference in days. Check docsYou have to add to your query QueryBuilder the
today
parameter.With the QueryBuilder, you can compare dates to DateTime with the format
'Y-m-d'
There is better option than adding the doctrine extension for date.
First you need to get start-datetime and end-datetime :
Now use them in query :
An easy solution would be to format the datetime accordingly
one idea is to extract from the date: the year, month and day. And then
MONTH DAY, and YEAR you take out the DoctrineExtensions from
e.g.
DoctrineExtensions
This works for me. You only need the files: day.php, month.php and year.php.....
You get the month e.g.:
Copy day.php, month.php and year.php to your bundle Xy\TestBundle\Dql Register the new functions in app\config.yml with