如何比较Doctrine2的日期时间字段与日期? [英] How to compare datetime field from Doctrine2 with a date?
问题描述
我想通过Doctrine2的QueryBuilder获取今天创建的项目。我想将createdAt(Datetime)字段与today参数(Date)进行比较。是否可以在一个查询中执行此操作?
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
推荐答案
一个想法是从日期提取:年,月和日。然后
one idea is to extract from the date: the year, month and day. And then
$qb->select('p')
->where('YEAR(p.postDate) = :year')
->andWhere('MONTH(p.postDate) = :month')
->andWhere('DAY(p.postDate) = :day');
$qb->setParameter('year', $year)
->setParameter('month', $month)
->setParameter('day', $day);
MONTH DAY,YEAR you take out the DoctrineExtensions from
MONTH DAY, and YEAR you take out the DoctrineExtensions from
例如
这对我有用。你只需要这些文件:day.php,month.php和year.php .....
This works for me. You only need the files: day.php, month.php and year.php.....
你得到这个月例如:
$datetime = new \DateTime("now");
$month = $datetime->format('m');
echo $month;
将day.php,month.php和year.php复制到您的包中Xy\TestBundle\ Dql
使用
Copy day.php, month.php and year.php to your bundle Xy\TestBundle\Dql Register the new functions in app\config.yml with
doctrine:
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
default:
auto_mapping: true
dql:
datetime_functions:
month: Xy\TestBundle\Dql\Month
year: Xy\TestBundle\Dql\Year
day: Xy\TestBundle\Dql\Day
这篇关于如何比较Doctrine2的日期时间字段与日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!