DQL select all users and count the number of reservations of each - php

I'm trying to select all my users and, for each user, count the number of reservations made and incoming. For the moment I have this
$qb = $this->createQueryBuilder('user');
return $qb->select('user')
->leftJoin('user.reservations', 'reservations')
->leftJoin('reservations.marketDate', 'market_date')
->addSelect('COUNT(nb_reservations FROM reservations WHERE market_date.date >= CURRENT_DATE())')
->orderBy('user.name')
->groupBy('user.id')
->getQuery()
->getResult();
But I have this error
[Semantical Error] line 0, col 59 near 'market_date >=': Error: Class
'market_date' is not defined.
Please help me

Try this:
$qb = $this->createQueryBuilder('user');
return $qb->select('user, count(reservations) as count')
->leftJoin('user.reservations', 'reservations')
->leftJoin('reservations.marketDate', 'market_date')
->where('market_date.date >= CURRENT_DATE()')
->orderBy('user.name')
->groupBy('user.id')
->getQuery()
->getResult();

The syntax in the COUNT does not seem correct: the COUNT should not include the whole statement. Try this:
->addSelect('COUNT(nb_reservations) FROM reservations WHERE market_date.date >= CURRENT_DATE()')

Related

Symfony Doctrine Group By Query

I have below sql query running fine,
SELECT completed_by, count(*) AS Total
FROM tasks
WHERE completed_by is not null AND status = 1
GROUP BY completed_by
;
Em am doing it with doctrine query builder, but not working returning an error.
$parameters = array(
'status' => 1,
);
$qb = $repository->createQueryBuilder('log');
$query = $qb
->select(' log.completedBy, COUNT(log) AS Total')
->where('log.Status = :status')
->groupBy('log.completedBy')
->setParameters($parameters)
->getQuery();
and getting below error;
[Semantical Error] line 0, col 21 near 'completedBy,': Error: Invalid
PathExpression. Must be a StateFieldPathExpression.
I know this answer can be late, but I struggled with the exact same problem, and did not find any answer on the internet, and I believe a lot of people will struggle in this same issue.
I'm assuming your "completedBy" refers to another entity.
So, inside your repository, you can write:
$query = $this->createQueryBuilder("log")
->select("completer.id, count(completer)")
->join("log.completedBy", "completer")
->where('log.Status = :status')
->groupBy("completer")
->setParameters($parameters)
->getQuery();
This will compile to something like:
SELECT completer.id, count(completer) FROM "YOUR LOG CLASS" log INNER JOIN log.completedBy completer WHERE log.Status=:status GROUP BY completer
Now, You can do another query to get those 'completers', by their ids.
This is wrong: COUNT(log) AS Total. It should be something like COUNT(log.log) AS Total.
When you want to select a column who is a fk for another table (entity), use the IDENTITY function instead of the column name only.
Example: In your case
$parameters = array(
'status' => 1,
);
$qb = $repository->createQueryBuilder('log');
$query = $qb
->select('IDENTITY(log.completedBy), COUNT(log.something) AS Total')
->where('log.Status = :status')
->groupBy('log.completedBy')
->setParameters($parameters)
->getQuery();

How to use DATE_ADD to compare date in range in Doctrine and Symfony2 using createQueryBuilder

I have two tables related to each other (main_table OneToMay detail_table). There is a deadline_days field in main table and a create_date in detail_table. I want to select all details which create_date+main.deadline_days are passed base on today date. (This was the scenario)
This is the proper MySQL query which gives me right records
SELECT `D`.* FROM `details_table` AS `D`
INNER JOIN `main_table` AS `M` ON (`D`.`Main_Id` = `M`.`id`)
WHERE DATE_ADD(`D`.`Create_Date`, INTERVAL `M`.`Deadline_days` DAY) <= NOW()
Now in Symfony when I want to create the query using createQueryBuilder it comes with this error
[Syntax Error] line 0, col 165: Error: Expected Doctrine\ORM\Query\Lexer::T_COMMA, got 'M'
This is what I have for now in my query builder
$result = $this->createQueryBuilder('D')
->join('D.Main', 'M')
->where('DATE_ADD(D.Create_Date, INTERVAL M.DeadLine_Days DAY) <= NOW()')
->getQuery()
->getResult();
Any idea how to fix this?
Thanks in advance.
Please do not suggest using native query
This is what I found base on this link (Doctrine Update DQL function signature)
Doctrine2 has function DATE_ADD but does not have INTERVAL param as MySQL, also the unit param should be as string 'DAY'; so the Query should be:
$result = $this->createQueryBuilder('D')
->join('D.Main', 'M')
->where('DATE_ADD(D.Create_Date, M.DeadLine_Days, 'DAY') <= CURRENT_DATE()')
->getQuery()
->getResult();
In doctrine we should use CURRENT_DATE() instead of NOW()

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)

How to select fields using doctrine 2 query builder

I have the following query I'm executing in Symfony2 Repository. The query looks like
$q = $this
->createQueryBuilder('m')
->select(array('m.reciever','m.created','m.id','m.subject'))
->where('m.reciever = ?1')
->orderBy('m.id','DESC')
->setMaxResults( '?2' )
->setFirstResult( '?3' )
->setParameter(1,$id)
->setParameter(2,$itemsPerPage)
->setParameter(3,$offset)
->getQuery();
Where reciever, created, id, and subject are fields part of my message entity. I do not need to specify which entity I am selecting from. The error I keep getting is such...
[Semantical Error] line 0, col 12 near 'reciever, m.created,': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
I'm not sure what a state field path expression is or what the syntax might be. It seems like everything should be right.
When you use the select() method, you override the default one which is in $this->createQueryBuilder('m') . That's why you lost the m alias. To avoide this, use an addSelect() or specify the alias in the from() method:
->from('Bundle:Entity', 'ALIAS')
Do you have something like this:=?
$q = $this
->createQueryBuilder()
->select('m.reciever, m.created ,m.id , m.subject')
->from('/Acme/Entity/DemoEntity', 'm')
->where('m.reciever = ?1')
->orderBy('m.id','DESC')
->setMaxResults( '?2' )
->setFirstResult( '?3' )
->setParameter(1,$id)
->setParameter(2,$itemsPerPage)
->setParameter(3,$offset)
->getQuery();
Im not sure but I think you use the array syntax only if you have multiple tables to join together: array('m.reciever, m.created', 'p.user, p.id').
i hope this will help u..
$em = $this->getDoctrine()->getManager();
$q = $em->createQueryBuilder()
->select('m.reciever,m.created,m.id,m.subject')
->from('bundle:entity','m')
->where('m.reciever = ?1')
->orderBy('m.id','DESC')
->setMaxResults( '?2' )
->setFirstResult( '?3' )
->setParameter(1,$id)
->setParameter(2,$itemsPerPage)
->setParameter(3,$offset)
->getQuery();

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