From raw sql query to symfony 2 sql query - symfony

I have this sql query:
SELECT * from gift WHERE NOW() >= `validbegin` AND NOW() <= `validend` ORDER BY `points`n ASC
I need to transform it to a Symfony 2 query to fetch the data to an object call Gift. So far I have this:
$query = $giftRepository->createQueryBuilder('p')
->where('NOW() >= validbegin AND NOW() <= p.validend')
->orderBy('p.points', 'ASC')
->getQuery();
$gifts = $query->getResult();
But that gave me:
[Syntax Error] line 0, col 53: Error: Expected known function, got
'NOW'
Any idea?
ps. Also tried p.NOW()

Try this :
$query = $giftRepository->createQueryBuilder('p')
->where(':now >= validbegin AND :now <= p.validend')
->setParameter('now', new \DateTime())
->orderBy('p.points', 'ASC')
->getQuery();
$gifts = $query->getResult();
You generate the field from php, then doctrine will automatically convert it to a mysql timestamp

Related

Comparing current date with stored dated on doctrine querybuilder

I need to make a query to get the row where the active field is true or the current date is between two stored dates Itring with
$qb->andWhere('p.active = true')')
->orWhere($qb->expr()->andX(
$qb->expr()->lt('p.activationDate', 'now()'),
$qb->expr()->eq('p.deactivationDate', 'now()')
))
->setMaxResults(1);
But I get :
[Syntax Error] line 0, col 145: Error: Expected known function, got 'now'
the were can be like this:
->andWhere("CURRENT_TIMESTAMP() BETWEEN p.activationDate and p.deactivationDate")
like this:
$repo = $this->em->getRepository(YourRepo::class);
$result = $repo->createQueryBuilder("p")
->andWhere("CURRENT_TIMESTAMP() BETWEEN p.activationDate and p.deactivationDate")
->getQuery()
->getResult();

Doctrine Query Builder Bug?

I have run into an issue in Doctrine. I have built the following query with queryBuilder
$qb = $query = $this->repoLibrary->createQueryBuilder('l');
$query = $qb
->innerJoin('l.productVariant', 'v')
->innerJoin('v.product', 'p')
->innerJoin('p.taxons', 't', 'WITH', 't.id IN (:array)')
->where('l.user = :user')
->groupBy('l.id HAVING count(DISTINCT t.id) >= :count')
->setParameter('user', $user)
->setParameter('array', $s)
->setParameter('count', count($taxons))
->getQuery();
Here is the query that is logged prior to execution:
SELECT s0_.id AS id0, s0_.consumed_at AS consumed_at1, s0_.created_at AS created_at2, s0_.updated_at AS updated_at3, s0_.user_id AS user_id4, s0_.variant_id AS variant_id5
FROM src_library s0_
INNER JOIN src_variant s1_ ON s0_.variant_id = s1_.id
INNER JOIN src_product s2_ ON s1_.product_id = s2_.id
INNER JOIN src_taxon_product s4_
ON s2_.id = s4_.product_id
INNER JOIN src_taxon s3_ ON s3_.id = s4_.taxon_id
AND (s3_.id IN (1,4))
WHERE s0_.user_id = 1
GROUP BY s0_.id HAVING count(DISTINCT s3_.id) = ? ["1,4",1,2]
When I execute this query (after inserting the parameters seen above) directly in MySQL it works perfectly, returning the 2 results that I'm looking for.
However, when it is executed by Doctrine it returns an empty array.
Any Ideas??
After scouring the interwebs I found the following answer. The problem is with the 'IN' clause. As articulated here:
https://groups.google.com/forum/#!topic/doctrine-dev/-_cINyk2dvs
My problem was being caused by the fact that I was building the 'IN' array as a string.
$s = "1,4"
instead of
$s = array(1,4);
This made all the difference in the world, and also made me feel like a n00b.
Your code looks fine and should work. I can't see your whole code but I'm guessing that it is returning an empty array because you have not actually executed the prepared sql statement yet. You should call the "getResult()" to do this.
Try this:
$qb = $query = $this->repoLibrary->createQueryBuilder('l');
$query = $qb
->select('l, v.id, p.id')
->innerJoin('l.productVariant', 'v')
->innerJoin('v.product', 'p')
->innerJoin('p.taxons', 't', 'WITH', 't.id IN (:array)')
->where('l.user = :user')
->groupBy('l.id HAVING count(DISTINCT t.id) >= :count')
->setParameter('user', $user)
->setParameter('array', $s)
->setParameter('count', count($taxons))
->getQuery()
->getResult();

query with dateformat in where clause in symfony2

when I run a query with date in where clause, following error is showed...
[Syntax Error] line 0, col 129: Error: Expected known function, got 'DATE_FORMAT'
the query is given below
$query = $this->getEntityManager()->createQuery(
"SELECT a.id, a.amont, a.paymentDescrip, a.paymentType, a.paymentDate
FROM RegalSmsBundle:DailyTransaction a
WHERE DATE_FORMAT(a.paymentDate,'%Y-%m-%d') = :paymentDate
and a.students = :studentId"
)->setParameter('studentId', $studentId)
->setParameter('paymentDate','2013-03-11');
return $query->getResult();
Doctrine doesn't have DATE_FORMAT function defined by default. It's possible to Register Custom DQL Function.
But you can compare date easily (assuming a.paymentDate is of type date):
$query = $this->getEntityManager()->createQuery("
SELECT a.id, a.amont, a.paymentDescrip, a.paymentType, a.paymentDate
FROM RegalSmsBundle:DailyTransaction a
WHERE a.paymentDate = :paymentDate AND a.students = :studentId
")
->setParameter('studentId', $studentId)
->setParameter('paymentDate', new \DateTime('2013-03-11'))
;
return $query->getResult();
Edit: I prefer using querybuider to writing DQL. It would look like this:
$qb = $this->getEntityManager()->getRepository('RegalSmsBundle:DailyTransaction')->createQueryBuilder('a');
$qb
->select('a') // select whole entity
->where($qb->expr()->andX(
$qb->expr()->eq('a.paymentDate', ':paymentDate')
$qb->expr()->eq('a.students', ':studentId')
))
->setParameter('studentId', $studentId)
->setParameter('paymentDate', new \DateTime('2013-03-11'))
;
return $qb->getQuery()->getResult();

'where not in' query with doctrine query builder

Im trying to reproduce this query:
SELECT * FROM `request_lines`
where request_id not in(
select requestLine_id from `asset_request_lines` where asset_id = 1
)
in doctrine query builder,
I am stuck on the where request_id not in(select
I currently have:
$linked = $em->createQueryBuilder()
->select('rl')
->from('MineMyBundle:MineRequestLine', 'rl')
->where()
->getQuery()
->getResult();
You need to use query builder expressions, and this means you need access to the query builder object. Also, the code is easier to write if you generate the subselect list ahead of time:
$qb = $em->createQueryBuilder();
$nots = $qb->select('arl')
->from('$MineMyBundle:MineAssetRequestLine', 'arl')
->where($qb->expr()->eq('arl.asset_id',1))
->getQuery()
->getResult();
$linked = $qb->select('rl')
->from('MineMyBundle:MineRequestLine', 'rl')
->where($qb->expr()->notIn('rl.request_id', $nots))
->getQuery()
->getResult();
It is possible to do this in one Doctrine query:
$qb = $this->_em->createQueryBuilder();
$sub = $qb;
$sub = $qb->select('arl')
->from('$MineMyBundle:MineAssetRequestLine', 'arl')
->where($qb->expr()->eq('arl.asset_id',1));
$linked = $qb->select('rl')
->from('MineMyBundle:MineRequestLine', 'rl')
->where($qb->expr()->notIn('rl.request_id', $sub->getDQL()))
->getQuery()
->getResult();
Check the reference in this answer here
Using Symfony 5, this solution might help those, who are trying to set parameters on a subquery, the notIn() 2nd argument accepts an array or you could pass a DQL instead and that's what we are doing here and keep in mind that the parameters should be added to the main query as below.
$main = $this->em->createQueryBuilder();
$sub = $main;
$sub = $sub->select('arl')
->from('$MineMyBundle:MineAssetRequestLine', 'arl')
->where($sub->expr()->eq('arl.asset_id',':id'));
$linked = $main->select('rl')
->from('MineMyBundle:MineRequestLine', 'rl')
->where($main->expr()->notIn('rl.request_id', $sub->getDQL()))
->setParameter('id', 1)
->getQuery()
->getResult();

update doctrine with join table

I am trying to update the field "note" in Note Entity which have a relation ManyToOne (bidirectionnel) with "ElementModule" and "Inscription", the entity "Inscription" have a relation ManyToOne with the "Etudiant" Entity
I tried this DQL Query:
$query = $this->_em->createQuery('update UaePortailBundle:Note u JOIN u.inscription i JOIN u.elementmodule e join i.etudiant et set u.note = ?3
where et.id = ?1 and e.id = ?2 ');
$query->setParameter(1, $etudiant);
$query->setParameter(2, $element);
$query->setParameter(3, $note);
$resultat = $query->execute();
i get this error
[Syntax Error] line 0, col 50: Error: Expected Doctrine\ORM\Query\Lexer::T_EQUALS, got 'i'
LEFT JOIN, or JOINs in particular are only supported in UPDATE statements of MySQL. DQL abstracts a subset of common ansi sql, so this is not possible. Try with a subselect or IDENTITY ( you must use the latest version of Doctrine 2.2.2 ) :
createQuery('update UaePortailBundle:Note u set u.note = ?3
where IDNETITY(u.inscription) = ?1 and IDENTITY(u.elementmodule) = ?2 ');
after searching and trying to find a solution for that using doctrine dql, i was not able to find it, so i used direct sql query to update the database.
$stmt = $this->getEntityManager()
->getConnection()
->prepare("update note set note = :note where `etudiant_id` like :etudiant_id and `elementmodule_id` like :elementmodule_id");
$stmt->bindValue('etudiant_id',$etudiant);
$stmt->bindValue('elementmodule_id' ,$element );
$stmt->bindValue('note', $note);
$stmt->execute();

Resources