Comparing current date with stored dated on doctrine querybuilder - symfony

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

Related

Doctrine error - expected end of string, got "ORDER"

Using Symfony 4 / Doctrine, I got an error with this query :
$this->createQueryBuilder('s')
->update()
->set('s.dateCreate', ':date_new')
->setParameter('date_new', date('Y-m-d H:i:s'))
->where('s.site = :site')
->setParameter('site', $site)
->orderBy('s.dateCreate', 'DESC')
->setMaxResults(1)
->getQuery()
->execute();
I got this error :
[Syntax Error] line 0, col 81: Error: Expected end of string, got 'ORDER'
If I remove the orderBy, query works but I need to only update last entry. Can't see what is wrong here..
You are make an update statement, where inside it you can't add an order by function in this case.
If you want to order your result you need to make a select instead of an update into another query, you can do both, or you need to make a subselect to update only 1 result for example

Symfony and Doctrine: order by time difference

I am trying to build a query that retrieves all the most recent and upcoming activities from database.
The entity activity has a field named date of type DateTime. So in my repository I was thinking of building something like this:
$query = $repository
->createQueryBuilder('a');
$query->orderBy( 'DATEDIFF( a.date, NOW())' , 'ASC');
$query->setMaxResults( 6 );
return $query;
Unfortunately I get the following error:
[Syntax Error] line 0, col 59: Error: Expected end of string, got '('
The Dql that is generated by my query:
SELECT a FROM MyBundle\Entity\Activity a ORDER BY DATEDIFF( a.date, NOW()) ASC
I also tried installing beberlei/DoctrineExtensions, but either it is not working or I was unable to configure it correctly.
Anyone has any suggestion?
Thanks in advance
date_diff si already implemented as Doctrine DQL statement as described here
for use as ordering statement I suggest you to use the HIDDEN select keyword as explained in this article
So your DQL is like this:
SELECT
a,
DATE_DIFF( a.date, CURRENT_TIMESTAMP() ) AS HIDDEN score
FROM MyBundle:Entity a
ORDER BY score
And add the max result on the query. Let me know if you need help to adapt as query builder statement
Hope this help
Why don't you just use
$query = $repository
->createQueryBuilder('a');
$query->orderBy( 'DATEDIFF( a.date, CURRENT_TIMESTAMP())' , 'ASC');
$query->setMaxResults( 6 );
return $query;
?

Symfony createQueryBuilder with many to many

In my system candidate and profession has many to many relationship. I need to implement following query in symfony.
SELECT c. *
FROM candidate AS c
LEFT JOIN candidate_profession AS cp ON cp.candidate_id=c.id
WHERE cp.profession_id = 2
So i wrote following code.
$matched = $em->getRepository('AppBundle:Candidate')
->createQueryBuilder('c')
->where('c.professions = :profession')
->setParameter('profession', $job->getProfession())
->getQuery()
->getResult();
$job->getProfession() is return profession object. But it show following error.
[Semantical Error] line 0, col 51 near 'professions =': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.
How i implement that query?
I think your query should look like this:
$em->getRepository('AppBundle:Candidate')
->createQueryBuilder('c')
->leftJoin('c.professions', 'p')
->where('p.id = :profession')
->setParameter('profession', $job->getProfession())
->getQuery()
->getResult();
More about join clauses: http://doctrine-dbal.readthedocs.org/en/latest/reference/query-builder.html#join-clauses
First of all, I don't know where you have placed that snippet of code but I strongly advice you to migrate it into a Repository if you don't have already done (but looking at code I'm not sure you have)
Second, you need to pass an ID as ->getProfession() (as you already noticed) will return the whole object and you don't need it
So your query should be like this
$matched = $em->getRepository('AppBundle:Candidate')
->createQueryBuilder('c')
->where('c.professions = :profession')
->setParameter('profession', $job->getProfession()->getId())
->getQuery()
->getResult();
Please pay attention
You didn't specify the cardinality of relationship between job and profession: if is a something-to-Many you can't simply use ->getId() as returned object is an ArrayCollection, so, in that case, you need to do a loop to extract all id(s) and then use something like "IN" clause

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

From raw sql query to symfony 2 sql query

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

Resources