Get data from previous month in Doctrine2 - symfony

I need to all data from the table that were created in last month. I've create below code but it gives below error in DQL, however the SQL query is correct when run it.
Error :
[Syntax Error] line 0, col 138: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got '-'
Code is;
$compCases = $this->getDoctrine()
->getRepository('EFuturesCrmBundle:CasesCompensation')
->createQueryBuilder('c')
->select('c.id')
->where('c.caseStatus =:status')
->andWhere('YEAR(c.caseStatusDate) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)')
->andWhere('MONTH(c.caseStatusDate) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)')
->setParameter('status', 'resolve')
->getQuery()
->getResult();
DQL is not support to the INTERVAL so how this possible in Doctrine2 ?

Try to use this kind of approach:
$now = new \DateTime('now');
$delay = new \Datetime('last month');
$compCases = $this->getDoctrine()
->getRepository('EFuturesCrmBundle:CasesCompensation')
->createQueryBuilder('c')
->select('c.id')
->where('c.caseStatus = :status')
->andWhere('c.caseStatusDate <= :now')
->andWhere('c.caseStatusDate >= :delay')
->setParameter('status', 'resolve')
->setParameter('now', $now)
->setParameter('delay', $delay)
->getQuery()
->getResult();
Hope it can help you.

Related

symfony querybuilder group function

i want get rows individually with condition that sum of prizes equals to my parameter (price)
actually i want limit number of rows in prize entity
but i get this error:
SQLSTATE[HY000]: General error: 1111 Invalid use of group function
this is my query :
$qb = $this->createQueryBuilder('up')
->join('up.prize','prize')
->select()
->where('up.user = :user')
->andWhere('SUM(prize.prizeValue) <= :price')
->setParameters(['user'=>$user , 'price'=>$price])
->getQuery()
->getResult();
return $qb;
You can't use aggregate function in WHERE clause.
Why are aggregate functions not allowed in where clause
Try this:
$qb = $this->createQueryBuilder('up')
->join('up.prize','prize')
->select('up')
->where('up.user = :user')
->having('SUM(prize.prizeValue) <= :price') // Replace with `having`
->setParameters(['user'=>$user , 'price'=>$price])
->groupBy('up') // `Group by` because you're using an aggregate
->getQuery()
->getResult();
return $qb;
You have to move the Where condition to the HAVING clause
$qb = $this->createQueryBuilder('up')
->join('up.prize','prize')
->where('up.user = :user')
->having('SUM(prize.prizeValue) <= :price')
->groupBy('up.id')
->setMaxResults(5);
->setParameters(['user'=>$user , 'price'=>$price]);
return $qb->getQuery()->getResult();

Doctrine Subquery undefined class when using MIN and MAX

I am creating a query that identifies the previous and later record for a given ID. I have the following code:
$min = $this->createQueryBuilder('t1')
->select('MIN(t1.id)')
->where('t.id = t1.id' )
->andWhere('t1.id > :id')
->andWhere('t1.type = :type');
$max = $this->createQueryBuilder('t2')
->select('MAX(t2.id)')
->where('t2.id > :id')
->andWhere('t2.type = :type')
->andWhere('t2.id = t.id');
return $this->createQueryBuilder('t')
->addSelect('(' . $min->getDQL() . ') AS min')
->addSelect('(' . $max->getDQL() . ') AS max')
->setParameter('id', $id)
->setParameter('type', $type)
->getQuery()
->getScalarResult();
However the above code throws an error saying:
[Semantical Error] line 0, col 138 near ', (SELECT MAX(t2.id)': Error: Class ',' is not defined.
Why is that so?
Thanks.
I think your problem is using min and max as alias. I got the same error when I used them, but changing the alias worked fine. I think you could also simplify your logic into one queryBuilder
$queryBuilder = $this->createQueryBuilder('story');
$queryBuilder
->select('MAX(story.id) AS max_id')
->addSelect('MIN(story.id) AS min_id')
->where('story.id > :id')
->setParameter('id', 1);
return $queryBuilder->getQuery()->getScalarResult();
Returned:
[
{
"max_id": "17",
"min_id": "16"
}
]

querybuilder query define parameter in symfony2

when i define a parameter in the given section its give me error that this "tt" parameter is undefine. i do not know what is the problem. it give me this error
Notice: Undefined property: Doctrine\ORM\QueryBuilder::$SELECT u1.unitid, m1.id FROM ApiMapBundle:Mappaths m1 INNER JOIN ApiMapBundle:Unitids u1 WITH m1.refUnitids2 = u1.id OR m1.refUnitids1 = u1.id WHERE m1.id=:tt
$cn=2;
$qb = $em->createQueryBuilder();
$query = $qb->select('u1.unitid','m1.id')
->from('ApiMapBundle:Mappaths', 'm1')
->join('ApiMapBundle:Unitids', 'u1', 'WITH', $qb->expr()->orX('m1.refUnitids2 = u1.id', 'm1.refUnitids1 = u1.id'))
->andWhere('m1.id=:tt')
->$qb->setParameter('tt', $cn)
->getQuery()
->getResult();
return $query;
any idea?
Try removing ->$qb from ->$qb->setParameter('tt', $cn)

doctrine dql exception: Illegal offset type in /var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php line 601

I want to produce a DQL for following MySQL query:
SELECT * FROM `folders` AS `t` WHERE `t`.`Library` = #myLib AND AND `t`.`Id` NOT IN (
SELECT DISTINCT(`f`.`Id`) FROM `folders` AS `f` JOIN `folders` AS `ff` ON (`f`.`Position` LIKE CONCAT(`ff`.`Position`, '%')) WHERE `ff`.`Active` = 1 AND `ff`.`Library` = #myLib AND `f`.`Library` = #myLib
)
ORDER BY `t`.`Position` ASC
The query works fine in mySQL and returns correct records.
To generate DQL I've tried both below options:
1.
$query = $em->createQuery("SELECT F FROM MyBundle:Folders T WHERE T.Library = :libid AND T.id NOT IN (
SELECT DISTINCT(F.id) FROM MyBundle:Folders F JOIN MyBundle:Folders FF WITH F.Position LIKE CONCAT(FF.Position, '%') AND F.Library = :libid AND FF.Library = :libid AND FF.Active = true
) ORDER BY T.Position ASC")
->setParameter('libid', $library);
$result = $query->getResult();
2.
$q1 = $this->createQueryBuilder('F')
->select('DISTINCT(F.id)');
$q1->join('\MyBundle\Entity\Folders', 'FF', 'WITH', $q1->expr()->like('F.Position', $q1->expr()->literal('CONCAT(FF.Position, \'%\')')))
->where('FF.Active = true')
->andWhere("FF.Library = '$library'")
->andWhere("F.Library = '$library'");
$q2 = $this->createQueryBuilder('T');
$q2->where('T.Library = :libid')
->andWhere($q2->expr()->notIn('T.id', $q1->getDQL()))
->setParameter('libid', $library)
->orderBy('T.Position', 'ASC');
$result = $q2->getQuery()->getResult();
In my perspective it seems OK but I don't know why in both ways it produce following exception:
ContextErrorException: Warning: Illegal offset type in
/var/www/Symfony/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php line 601
Any help will be appreciated.
It seems no one has an answer for this. I found a temporary solution as below (I call it temporary because I'm changing my unique query to two separate queries and it seems the issue is in core of doctrine).
$qb = $this->createQueryBuilder('F')
->select('DISTINCT(F.id)');
$qb->join('\MyBundle\Entity\Folders', 'FF', 'WITH', 'F.Position LIKE CONCAT(FF.Position, \'%\')')
->where('FF.Active = true')
->andWhere("FF.Library = :library")
->andWhere("F.Library = :library")
->setParameter('library', $library);
$included_folders = $qb->getQuery()->getArrayResult();
$query = $this->createQueryBuilder('F')
->where('F.Active = false')
->andWhere('F.Library = :library')
->setParameter('library', $library)
->orderBy('F.Position', 'ASC');
if (!empty($included_folders)) {
if (count($included_folders) > 1)
{
foreach ($included_folders as $index => $value)
{
if (is_array($value))
{
$included_folders[$index] = !empty($value['id']) ? $value['id'] : $value[1];
}
}
$query->andWhere($query->expr()->notIn('F.id', $included_folders));
}
else {
$query->andWhere('F.id != :folder ')
->setParameter('folder', $included_folders[0]);
}
}
$result = $query->getQuery()->getResult();
As you see instead of getting the dql from my first query and putting it inside my second dql in notIn section which will lead to the warning message, I execute the first query and get the results then put the results inside notIn if amount of returned values are more than one, otherwise it should be in regular !=. This solved my problem for now, but as you see amount of transactions are now increased
If anyone has a better solution or any fix for the warning I will be thankful.
I've encountered the same error and it seems that this has been fixed in latest trunk of Doctrine/ORM.
Using "2.5.*#dev" as version in your composer.json for doctrine/orm should fix this bug and will let you do what you want in a single query.

Symfony2 - Error when trying to get post count for a specific year

I am trying to create a query to find all posts within the year 2014.
I have the following but the error appears:
[Syntax Error] line 0, col 88: Error: Expected end of string, got '00'
What's wrong with my query?
public function getPostCountByYear()
{
$query = $this
->createQueryBuilder('post')
->where('created >= 2014-01-01 00:00:00 AND created < 2015-01-01 00:00:00');
$query->select('COUNT(post)');
$year = $query
->getQuery()
->getSingleScalarResult();
return $year;
}
Try this.
public function getPostCountByYear()
{
$query = $this
->createQueryBuilder('post')
->where('post.created >= :begin')
->andWhere('post.created < :end')
->setParameter('begin', new \DateTime('2014-01-01 00:00:00'))
->setParameter('end', new \DateTime('2015-01-01 00:00:00'));
$query->select('COUNT(post.created)');
$year = $query
->getQuery()
->getSingleScalarResult();
return $year;
}

Resources