Doctrine- Group by date - php

I have this query :
SELECT DATE_FORMAT(exp_date, "%Y-%m") AS Month, sum(exp_total) FROM export
GROUP BY DATE_FORMAT(exp_date, "%Y-%m");
I tried to convert it to Symfony doctrine like below :
$qb = $this
->createQueryBuilder('e')
->select('DATE_FORMAT(e.expDate, \'%Y-%m\'), sum(e.expTotal) total')
->groupBy('DATE_FORMAT(e.expDate, \'%Y-%m\')');
return $qb->getQuery()->getResult();
Using:
"beberlei/DoctrineExtensions": "^1.0"
Error: [Semantical Error] line 0, col 103 near
'DATE_FORMAT(e.expDate,': Error: Cannot group by undefined
identification or result variable.

I assume you have configured the mentioned bundle and added the required configuration like
doctrine:
orm:
dql:
datetime_functions:
date_format: DoctrineExtensions\Query\Mysql\DateFormat
Now in query you can assign an alias as dateAsMonth to the result of DATE_FORMAT expression and in group by you can use this alias
return $qb = $this->createQueryBuilder('e')
->select('DATE_FORMAT(e.expDate, \'%Y-%m\') as dateAsMonth, sum(e.expTotal) total')
->groupBy('dateAsMonth')
->getQuery()
->getResult();

Related

Doctrine DQL with SELECT, GROUP BY, COUNT Semantical Error

I'd like to perform query like:
SELECT o.lang, COUNT(o.id) FROM `order` o GROUP BY o.lang;.
I try:
$entityManager->getRepository(Order::class)
->createQueryBuilder('o')
->select(["o.baseLang", "COUNT(o.id)"])
->groupBy("o.baseLang")
->getQuery()
->getResult();
, but I get Error: Invalid PathExpression. Must be a StateFieldPathExpression.
How do I do this?
You put:
$entityManager->getRepository(Order::class)
->createQueryBuilder('o')
->select(["IDENTITY(o.baseLang)", "COUNT(o.id)"])
->groupBy("o.baseLang")
->getQuery()
->getResult();

Doctrine 2 Multiple select elements, aliases, date_format

i'm new with doctrine and want to make a query on my db using it
SELECT DATE_FORMAT(DATE(created_at), '%m-%Y') AS 'date',
COUNT(DISTINCT(id)) AS 'value'
FROM users
GROUP BY YEAR(DATE(created_at)), MONTH(DATE(created_at))
i read some documentation but still have few questions
how to i select multiple elements; give aliases to my selected elements, do a left join. Are WEEK() MONTH() and YEAR() functions avaible ? does DATE_FORMAT (from mysql) is avaible ?
thank you
I believe you should use the query builder (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html).
Considering date, you can use symfony datetime objects and format them.
For left join the leftJoin method can be used (http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/query-builder.html)
<?php
// $qb instanceof QueryBuilder
$qb->select('u as aliasName') //see for alias
->from('User', 'u')
->leftJoin('u', 'phonenumbers', 'p', 'u.id = p.user_id') //see for left join
->where('u.id = ?1')
->addwhere(u.date < :date)
->orderBy('u.name', 'ASC')
->setParameter('date', $symfonyDateTime->format('Y-m-d')); //see for date
Instead of QueryBuilder, you can also try DQL (http://symfony.com/doc/current/doctrine.html and http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html):
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p
FROM AppBundle:Product p
WHERE p.price > :price
ORDER BY p.price ASC'
)
->setParameter('price', 19.99);
$products = $query->getResult();
You could install doctrine extensions in order to use functions like:
DATE, MINUTE, HOUR, DAY, WEEK and many more.
Example:
Doctrine Configuration
doctrine:
dbal:
....
orm:
auto_generate_proxy_classes: "%kernel.debug%"
entity_managers:
default:
dql:
datetime_functions:
DATE_FORMAT: DoctrineExtensions\Query\Mysql\DATE_FORMAT
Then you can really easy add alias like this:
DATE_FORMAT(s.createdAt,'%Y-%m-01') as date

Get Records from database of all months

I am developing a web application in symfony. I want to fetch the records from database according to months. My Query is:
$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 is datetime field and stores in database like:
2015-06-12 11:50:44
I want records like
Jan=>5
Feb=>10
.....and so on..
Please Help
You can group your data by month and year with a DATE_FORMAT mysql statement.
In order to use the mysql function in a DQL Doctrine statement i suggest you to install the mapado/mysql-doctrine-functions doctrine function.
Simply add to your composer.json and enable it in the config.yml as follow:
#app/config/config.yml
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
default:
mappings:
....
dql:
datetime_functions:
date_format: Mapado\MysqlDoctrineFunctions\DQL\MysqlDateFormat
Then you can use in the repository as example:
$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();
You need to modify the example to add the count
Hope this help.
base query:
select count(last_updated), month(last_updated) from TABLENAME group by month(last_updated)
You can group by month in 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();
dont forget to add in your doctrine configuration:
doctrine:
orm:
dql:
string_functions:
MONTH: DoctrineExtensions\Query\Mysql\Month

Group By day and month Doctrine

I'd like to list my users by birthday, so month and day but not year.
I have this query
SELECT *
FROM user
WHERE birthDate IS NOT NULL
GROUP BY MONTH(birthDate), DAY(birthDate)
But I don't know how to use it with Symfony and Doctrine.
I tried
$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
->createQueryBuilder('user')
->where('user.birthDate IS NOT NULL')
->groupBy('MONTH(user.birthDate), DAY(user.birthDate)')
->getQuery()
->getResult();
And
$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
->createQueryBuilder('user')
->where('user.birthDate IS NOT NULL')
->groupBy('MONTH(user.birthDate)')
->groupBy('DAY(user.birthDate)')
->getQuery()
->getResult();
But in both cases I have an error
[Semantical Error] line 0, col 165 near 'MONTH(birthDate),': Error: Cannot group by undefined identification or result variable.
You haven't set an alias for your values. Here is an updated version :
$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
->createQueryBuilder('user')
->select(' user.username, MONTH(user.birthDate) AS gBmonth, DAY(user.birthDate) AS gBday')
->where('user.birthDate IS NOT NULL')
->groupBy('gBmonth')
->addGroupBy('gBday')
->getQuery()
->getResult();
This should work fine.
You can use one of these:
format(as.Date,)
or
strftime(source, format)

Doctrine2 LEFT JOIN exception

I've got a problem with Symfony/Doctrine2 doing SQL statement with two entites:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('s')
->from('basecomProductionWorkflowBaseBundle:SubprocessData', 's')
->leftJoin('basecomProductionWorkflowBaseBundle:ReleaseDay', 'r', Expr\Join::WITH, 'r.id = s.releaseDay')
->where(
$qb->expr()->andX(
$qb->expr()->eq('r.date', ':date'),
$qb->expr()->isNotNull('r.edition')
)
)
->setParameter('date', $date);
I got the following error message:
[Semantical Error] line 0, col 124 near 'r WITH r.id =': Error: Identification Variable basecomProductionWorkflowBaseBundle:ReleaseDay used in join path expression but was not defined before.
PS: Both tables have no relation to each other (it's a workaround fixing another problem). I've tested the same statement in phpmyadmin.
It should be:
->leftJoin('s.releaseDay', 'r')
You could also simplify the conditions this way:
->where('r.date = :date')
->andWhere('r.edition IS NOT NULL')
or:
->where('r.date = :date AND r.edition IS NOT NULL')
¿What Expr class are you using?
I choose incorrectly the Expr class some days ago and throw me same exception.
Try:
use Doctrine\ORM\Query\Expr;

Categories