Select AVG of rows using Query Builder - symfony

I want to select the average of columns 'note' from a table
'noteparagraphe' where
the id_paragraphe is a parameter ($ref), I tried this query but I'm getting nothing back !
$query=$this->get('doctrine.orm.entity_manager')
->createQuery('Select avg(n.note) from ParagrapheBundle:NoteParagraphe n
WHERE n.id_paragraphe = :idModele');
$query->setParameter('idModele', $ref);
$query->execute();
$avgNote = $query->getResult();
the SQL is : SELECT AVG(note) from note_paragraphe WHERE id_paragraphe=?

Use Query builder:
$query = $this->getDoctrine()->getRepository('ParagrapheBundle:NoteParagraphe');
$avgNote = $query->createQueryBuilder('n')
->select('avg(n.note)')
->where('n.id_paragraphe = :idModele')
->setParameter('idModele', $ref);
->getQuery();
See if that works - I haven't tried it, but I think it should work.

Related

update an arrayResult of doctrine

i this query i get all of phones with certain condition
and one thing that i want after that is to set isFirstInstalled of all phones in this query to 1
also i want data of this query for api result
what is the most optimize way for that
the simplest way is using the result of the query in foreach and set one by one to 1 ?!
i want the result of my query before updating
$isFirstNotInstalledCases = $em->getRepository(User::class)
->createQueryBuilder('u')
->select("u.phone as phone")
->addSelect("u.isFirstInstalled as isFirstInstalled")
->where("u.phone IN (:phone)")
->andWhere("u.isFirstInstalled = :isFirstInstalled")
->setParameters(['isFirstInstalled'=>0,'phone'=>$phones])
->getQuery()
->getArrayResult();
Try to avoid foreach if you have not to do logic, use update better. Something like this:
$qb = $this->_em->createQueryBuilder();
$q = $qb->update('App\User', 'u')
->set('u.isFirstInstalled', 1))
->where("u.phone IN (:phone)")
->andWhere("u.isFirstInstalled = :isFirstInstalled")
->setParameters(['isFirstInstalled'=>0,'phone'=>$phones])
->getQuery();
$p = $q->execute();

Doctrine Native query inside query builder join

I am working on a query on Doctrine 2 (with Symfony 2.8)
I have this query giving me relevant info:
$qb = $this->createQueryBuilder('ea');
$qb->join('ea.entity_b', 'eb')
->join('ea.entity_c', 'ec')
->join('ec.entity_d', 'ed')
->join('MainBundle:Entity_E', 'ee','WITH', 'ee.column1 = ea.id')
->join('MainBundle:Entity_F', 'ef', 'WITH', 'ea.column1 = ef.id');
Now, I need to add extra info to that query, but it comes from a native SQL, something like this:
SELECT * FROM DS ORDER BY id DESC LIMIT 1
And make sure that the id of the result from the native query is equal to ef.id
I hope I made any sense.
Thanks
Do you know DQL ?
Similar to SQL but adapted for Doctrine.
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
You can then do queries like :
<?php
$query = $em->createQuery("SELECT u FROM User u JOIN u.address a WHERE a.city = 'Berlin'");
$users = $query->getResult();

Doctrine query building select MAX

I would like to select everything + MAX value and receive only rows having max values.
$query = $this->createQueryBuilder('s');
$query->where('s.challenge = :challenge')->setParameter('challenge', $challenge);
$query->groupBy('s.score');
$query->getQuery();
return $query->select('s.*, MAX(s.score) AS max_score')->getQuery()->getResult();
How could I achieve this in doctrine? I am getting an error that * property is not found. I have tried to select them all one by one but no luck either.
Goal is to achieve something like this
SELECT user, challenge, whateverelse, MAX(score) FROM users_scores_table GROUP BY user_id
Please help ;)
It's too late, but I write this for the records.
You can use "as HIDDEN" in SELECT statements to remove a field of the final result, this way you can use it for ordering or grouping without modifying result fields.
In your example:
$query = $this->createQueryBuilder('s');
$query->select('s, MAX(s.score) AS HIDDEN max_score');
$query->where('s.challenge = :challenge')->setParameter('challenge', $challenge);
$query->groupBy('s.user');
$query->setMaxResults($limit);
$query->orderBy('max_score', 'DESC');
Here is a final working query
$query = $this->createQueryBuilder('s');
$query->select('s, MAX(s.score) AS max_score');
$query->where('s.challenge = :challenge')->setParameter('challenge', $challenge);
$query->groupBy('s.user');
$query->setMaxResults($limit);
$query->orderBy('max_score', 'DESC');
return $query->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();

Symfony2 Query Builder

I am trying to get records from a table where patentgroup_id is null. I tried this
$repository = $this->getDoctrine()->getRepository('MunichInnovationGroupPatentBundle:SvPatents');
$qb1 = $repository->createQueryBuilder('sv')
->select('sv')
->where('sv.patentgroup = :patentgroup')
->setParameter('patentgroup', null)
->getQuery();
$nogroup_patents = $qb1->getArrayResult();
var_dump($nogroup_patents);
There is one record in the table whose patentgroup_id is null but I am getting empty array.
Any ideas? What I am doing wrong
thanks
same way you would do it in SQL
->where('sv.patentgroup IS NULL')

Resources