Get Records from database of all months - php

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

Related

How to use IF statement in Doctrine Query Builder select

I have a doctrine statement to get all the fields from a table
->createQueryBuilder()
->select('u')
->from(User::class, 'u')
How can I add to this select an additional column based on a value in another column? This would be the mysql equivalent:
SELECT
u.*,
IF(u.group = 1, 'Yes', 'No') as isAdmin
FROM user u ...
I need to know how to do this in doctrine. Thanks.

Doctrine- Group by date

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();

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

Doctrine: Custom column alias with QueryBuilder

I have a function selecting all columns from a table, using QueryBuilder, and I would like to add a custom column to the resulting query. This is what I have:
$qb = $this->_em->createQueryBuilder();
$qb->select(array('c', 'a'))
->from('models\Car', 'c')
->leftJoin('c.account', 'a')
->where('a.admin = 0');
Now, I would like to add a 'days car was in store' column, which in standard MySQL would be:
((UNIX_TIMESTAMP(c.daySold) - UNIX_TIMESTAMP(c.dayArrived))/86400) as days_car_in_store
How can I achieve that by adding it to the constructed query above?
Try something like this:-
$sql = "((UNIX_TIMESTAMP(c.daySold) - UNIX_TIMESTAMP(c.dayArrived))/86400)";
$qb->add('select', new Expr\Select(array('c', "{$sql} as days_car_in_store")))

PHP: Doctrine: order joined records

I'm new to doctrine: I have a problem with the sorting of joined records.
A sample.
I've got an Article model which is associated with a Source model in 1 <-> n. The source model has a property called 'position' with an integer value.
Now I want to fetch an article with it's sources orderes by the position. My DQL looks like this:
$q = Doctrine_Query::create()
->select('a.title, s.content')
->from('Article a')
->leftJoin('a.Source s')
->where('a.id = ?')
->orderBy('s.position');
The result doesn't change if I edit the position.
Best regards,
Sebastian
Hmm... it should do. Maybe try either of these:
->orderBy('s.position DESC')
->orderBy('s.position ASC')
Yes, it looks OK. Try to generate the SQL from the DQL with getSqlQuery() and query the database with the result. If there is still the wrong output, it might by a problem with the data or more likely, with the DQL.
Perhaps you should include the column that you are using for the ordering (s.position), so try this:
$q = Doctrine_Query::create()
->select('a.title, s.content, s.position')
->from('Article a')
->leftJoin('a.Source s')
->where('a.id = ?')
->orderBy('s.position');

Categories