Symfony2 datetime queryBuilder(Symfony2 日期时间查询生成器)
问题描述
我在 Symfony2 项目中有 2 个 DateTime 类.我有实体 Stat,其中有 $date 属性.
I have 2 DateTime classes in Symfony2 project. I have entity Stat, in which have $date property.
/**
* @ORMColumn(type="date", length="11")
*/
protected $date;
我必须使用 createQueryBuilder 中的 DateTime 对象进行查询.我怎样才能做到这一点 ?例如:
I have to make queries using DateTime objects in createQueryBuilder. How can i do that ? For example:
$date_from = new DateTime('2012-02-01');
$date_to = new DateTime('2012-02-15');
我需要从 $date_from 和 $date_to 之间的表 stats(实体 Stat)中获取所有行.我应该如何使用 createQueryBuilder 编写查询?我当前的代码是:
I need to get all rows from table stats (entity Stat) between $date_from and $date_to. How should i write my query with createQueryBuilder ? My current code is:
$qb = $em->createQueryBuilder();
$query = $qb->select('s')
->from('ACMEMyBundleEntityStat', 's')
->where('s.date >= :date_from')
->andWhere('s.date <= :date_to')
->setParameter('date_from', $date_from)
->setParameter('date_to', $date_to)
->getQuery();
推荐答案
本杰明的回答是正确的,但缺少一个细节.这是正确的做法:
Benjamin's answer is correct, but it lacks one detail. This is the correct way to do it:
$qb->andWhere($qb->expr()->between('s.date', ':date_from', ':date_to'));
但是要设置参数,我需要这样做:
But to set parameters, I need to do like this:
$qb->setParameter('date_from', $date_from, DoctrineDBALTypesType::DATETIME);
$qb->setParameter('date_to', $date_to, DoctrineDBALTypesType::DATETIME);
如果我省略 DATETIME 类型,我会收到以下错误(请参阅 这里):
If I omit the DATETIME types, I get the following error (see here):
DateTime 类的对象无法转换为字符串
Object of class DateTime could not be converted to string
我正在使用 Doctrine DBAL 2.0.5,这种行为可能在更高版本的 Doctrine 中有所改变.
I am using Doctrine DBAL 2.0.5, this behaviour might have changed in later versions of Doctrine.
这篇关于Symfony2 日期时间查询生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Symfony2 日期时间查询生成器


基础教程推荐
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01