Doctrine DQL with SELECT, GROUP BY, COUNT Semantical Error - php

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

Related

Check if a value is in one of two columns with doctrine query builder

I'm attempting build a query that will check an entity Project and check two columns either project_owner or project_contributor where project contributor is a Many to One relation.
The query I attempted to make was this (in the project entity repository):
return $this->createQueryBuilder('p')
->where('p.project_owner = :val')
->orWhere(':val in p.project_contributors')
->setParameter('val', $value)
->getQuery()
->getResult()
;
The error I received was the following:
[Syntax Error] line 0, col 75: Error: Expected Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS, got 'p'
Clearly this is the wrong approach. What is the right one? I'm trying to understand the query builder better.
You can make an inner join of the many to one relation, and then filter those.
return $this->createQueryBuilder('p')
->innerJoin('p.project_contributors', 'pc')
->where('p.project_owner = :val')
->orWhere('pc.name = :val')
->setParameter('val', $value)
->getQuery()
->getResult()
;

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

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

Extra Where when using Join in Doctrine Query Language

i have the following code in my Entity Repository class:
$qb
->select('d')
->addOrderBy('d.dtrDate', 'DESC')
->where($qb->expr()->isNotNull('d.deletedAt'))
->leftJoin('d.user', 'u')
->where('u.id = :user_id')
->setParameter('user_id', $user->getId());
So basically, I dont want to select an entity where deletedAt property is not null. However it gives me a query like this:
>
SELECT
d0_.id AS id_0,
d0_.dtr_date AS dtr_date_1,
d0_.clock_in AS clock_in_2,
d0_.clock_out AS clock_out_3,
d0_.total_time AS total_time_4,
d0_.memo AS memo_5,
d0_.last_update_IP AS last_update_IP_6,
d0_.created_at AS created_at_7,
d0_.updated_at AS updated_at_8,
d0_.deleted_at AS deleted_at_9,
d0_.user_id AS user_id_10
FROM
daily_time_record d0_
LEFT JOIN user u1_ ON d0_.user_id = u1_.id
WHERE
u1_.id = ?
ORDER BY
d0_.dtr_date DESC
As you can see my first where is not being called. So how can i work on this?
You should read the documents, or read the ORM source to see how things work actually. TO be short, the answer to your question is:
$qb
->select('d')
->leftJoin('d.user', 'u')
->where($qb->expr()->isNotNull('d.deletedAt'))
->andWhere('u.id = :user_id')
->setParameter('user_id', $user->getId())
->orderBy('d.dtrDate', 'DESC');

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

Categories