如何比较Doctrine2的日期时间字段与日期? [英] How to compare datetime field from Doctrine2 with a date?

查看:205
本文介绍了如何比较Doctrine2的日期时间字段与日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过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

例如

DoctrineExtensions

这对我有用。你只需要这些文件: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆