CASE WHEN not working doctrine2 query builder - doctrine-orm

I've written the following code to build the query using query builder.
$em = $this->_em;
$qb = $em->createQueryBuilder();
$qb->select('tbl');
$qb->addSelect('COUNT(tbl.macId) AS totalInstallations');
$qb->addSelect('COUNT(DISTINCT tbl.macId) AS uniqueInstallations');
$qb->addSelect('COUNT(CASE
WHEN tbl.updatedOn IS NOT NULL THEN tbl.macId ELSE NULL
END) AS totalUninstallations');
$qb->from('Entity\SoftwareInstallation', 'tbl');
$result = $qb->getQuery()->getArrayResult();
return $result;
But it's not working in the case condition.
I get the below error:
Type: Doctrine\ORM\Query\QueryException
Message: [Syntax Error] line 0, col 152: Error: Expected
Doctrine\ORM\Query\Lexer::T_FROM, got '.'
Filename:
/var/www/html/ghostnew/application/vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php
Line Number: 52

Try using SUM() instead of COUNT().
See this answer: Doctrine 2 DQL CASE WHEN in Count

Related

Doctrine: Sub-query where main entity id is in array of sub-query

I would like to search for people who are not allocated to a room. I made the following query:
public function findByWithoutRoom()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb2 = $this->getEntityManager()->createQueryBuilder();
$qb
->select('p')
->from('MyPeopleBundle:Person', 'p')
->where(
$qb->expr()->exists(
$qb2->select('r')
->from('MyAccommodationBundle:Room', 'r')
->andWhere($qb2->expr()->like('r.currentPeople', ':person'))
->setParameter('person', '%i:'.$person_id.';%')
->getDQL()
)
)
$result = $qb->getQuery()->execute();
return $result;
}
How can I have p.id instead of person_id? Note:The currentPeople property is of type "array" (not "simple_array")
UPDATE:
I also tried the following:
public function finByWithoutRoom()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb
->select('p')
->from('MyPeopleBundle:Person', 'p')
->leftJoin('MyAccommodationBundleV2:Room', 'r')
->andWhere($qb->expr()->like('r.currentPeople', '%i:p.id%'));
$result = $qb->getQuery()->execute();
return $result;
}
however this gave me the following error:
[Syntax Error] line 0, col 114: Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got '%'
You can use directly the alias of the main query, as example:
$qb
->select('p')
->from('MyPeopleBundle:Person', 'p')
->where(
$qb->expr()->isNotNull(
$qb2->select('r')
->from('MyAccommodationBundle:Room', 'r')
->andWhere($qb->expr()->like('r.currentPeople', 'p.id'))
->getDQL()
)
)
->setParameter('from', $from)
->setParameter('to', $to);
I suggest to use an not exists instead of is not null (I think is the same result however). As Example:
$qb->andWhere($qb->expr()->not($qb->expr()->exists($qb2->getDQL())));
Hope this help

Doctrine delete With Querybuilder an IN

$qb = $this->getDoctrine ()->getEntityManager()->createQueryBuilder();
$qb->delete('MainBundle:StatisticUser', 'u');
$qb->where($qb->expr()->in('sessionid', array_keys($sessionidsToTruncate)));
var_dump($qb->getQuery());
$qb->getQuery()->execute();
private '_dql' => string 'DELETE MainBundle:StatisticUser u WHERE sessionid IN('asdfghjkl')' (length=75)
but i get an error
[Semantical Error] line 0, col 50 near 'sessionid IN': Error: 'sessionid' is not defined.
Can anyone point me to the Problem?
Ok i found the solution with trial and error:
$qb->andWhere($qb->expr()->in('u.sessionid', array_keys($sessionidsToTruncate)));

doctrine 2 querybuilder like inside having

When using QueryBuilder object with like inside having as below:
$queuebuilder->addSelect('c.customercount*5 as count');
$queuebuilder->add('having', 'count like \'sometext\'');
I get an error:
[Syntax Error] line 0, col 741: Error: Expected '.' or '(', got count
This happpens only with aliased coloumn. How to avoid the error?
thank you.
Try something like this:
$qb->select('count(c.customer) as count');
$qb->having('count > x');
If you want to include where statements you could do something like this:
$qb->select('count(c.customer) as count');
$qb->where('c.username = :username');
$qb->having('count > ?1');
$qb->setParameter('username', "foo");
$qb->setParameter(1, 3); //havin count > 3

Doctrine error "Invalid parameter number: number of bound variables does not match number of tokens"

I'm building a Symfony 1.4.20 application and I wrote this code:
public function getListForAdmin() {
$user = sfContext::getInstance()->getUser();
$q = $this->createQuery('g');
if ($user->hasCredential('can_admin_full')) {
$q->addWhere('g.name IN (?)', array('Administradores Monitor', 'Monitor'));
} else if ($user->hasCredential('can_admin')) {
$q->addWhere('g.name IN (?)', array('Monitor'));
}
return $q;
}
Seeing in Symfony logs the result query is as follow:
SELECT s.id AS s__id, s.name AS s__name, s.description AS s__description, s.created_at AS s__created_at, s.updated_at AS s__updated_at
FROM sf_guard_group s
WHERE (s.name IN ('Administradores Monitor'))
I run the query in phpMyAdmin and all is fine meaning query doesn't have any problem but in Symfony with Doctrine I get this error:
SQLSTATE[HY093]: Invalid parameter number: number of bound variables
does not match number of tokens
Why? What's wrong?
I think that problem in this rows:
$q->addWhere('g.name IN (?)', array('Administradores Monitor', 'Monitor'));
and
$q->addWhere('g.name IN (?)', array('Monitor'));
It should be:
$q->whereIn('g.name', array('Administradores Monitor', 'Monitor'));
and
$q->whereIn('g.name', array('Monitor'));
UPDATE: edit answer

How to use IF statement that provided by DoctrineExtensions

I'm playing with DoctrineExtensions but can not manage it. After register DoctrineExtensions, I have following line of DQL with Zend Framework:
$qb->having(new IfElse("A.type = 0", new FindInSet(1, new GroupConcat('B.id', ',')) >0 , '1') );
But get this error msg:
Exception information:
Message: Expression of type 'DoctrineExtensions\Query\Mysql\IfElse'
not allowed in this context.*
Could you help me to point out what incorrect in my command or any document on how to use DoctrineExtensions?
UPDATED:
I've found a the way to implement custom function by :
I have given it a litle try by adding this line to boostrap:
$config->addCustomStringFunction('IF', 'DoctrineExtensions\Query\Mysql\IfElse');
And use it in DQL as:
$qb->having("IF( A.type = 0, S.status = 0, S.status = 1 )");
But get this error:
Message: [Syntax Error] line 0, col 152: Error: Expected Doctrine\ORM\Query\Lexer::T_COMMA, got '='
Maybe I'm wrong in syntax?
Have you tried
$qb->having("S.status = IF( A.type = 0, 0, 1 )");