我正在symfony中开发一个Web应用程序。我想根据月份从数据库中获取记录。我的查询是:
$totalSearchesByAdminAll = $em->createQueryBuilder()
->select('count(SearchHistory.id) AS totalSearchesByAdmin')
->from('DRPAdminBundle:Log', 'SearchHistory')
->where('SearchHistory.last_updated like :last_updated')
->setParameter('last_updated',??????.'%')
->andwhere('SearchHistory.event = :event')
->setParameter('event','ADMIN_SEARCH')
->getQuery()
->getArrayResult();
last_updated是datetime字段并存储在数据库中,如: 2015-06-12 11:50:44
我想要记录 扬=大于5 二月=大于10 .....等等..
请帮助
答案 0 :(得分:2)
您可以使用DATE_FORMAT
mysql语句按月和年对数据进行分组。
为了在DQL Doctrine语句中使用mysql函数,我建议你安装mapado/mysql-doctrine-functions doctrine函数。 只需添加到您的composer.json并在config.yml中启用它,如下所示:
#app/config/config.yml
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
default:
mappings:
....
dql:
datetime_functions:
date_format: Mapado\MysqlDoctrineFunctions\DQL\MysqlDateFormat
然后您可以在存储库中使用示例:
$qb = $this->createQueryBuilder('p')
->select("DISTINCT DATE_FORMAT(p. last_updated,'%m-%Y') as formatted_date")
->andwhere('p.SearchHistory.event = :event')
->setParameter('event','ADMIN_SEARCH')
->addGroupBy("formatted_date")
->orderBy('p.last_updated')
->getQuery()
->getResult();
您需要修改示例以添加计数
希望得到这个帮助。
答案 1 :(得分:1)
基本查询:
@registration.errors.messages[:event].delete('has already been taken')
答案 2 :(得分:1)
您可以在SQL中按月分组:
$totalSearchesByAdminAll = $em->createQueryBuilder()
->select('count(SearchHistory.id) AS totalSearchesByAdmin')
->addSelect('MONTH(last_updated) AS month')
->from('DRPAdminBundle:Log', 'SearchHistory')
->where('SearchHistory.last_updated >= :last_updated')
->setParameter('last_updated','2015-06-12 11:50:44')
->andwhere('SearchHistory.event = :event')
->setParameter('event','ADMIN_SEARCH')
->groupBy('month')
->getQuery()
->getArrayResult();
别忘了添加你的学说配置:
doctrine:
orm:
dql:
string_functions:
MONTH: DoctrineExtensions\Query\Mysql\Month