How to execute DQL query in Symfony2? - php

I am trying to get objects from DQL query.
Here is my code :
$em = $this->getDoctrine()->getRepository(Item::class);
$items = $em->createQuery($getQuery);
$items = $query->getResult();
$getQuery = DQL query string : SELECT from Entity WHERE ...
I am receiving error : Undefined method 'createQuery'. The method name must start with either findBy or findOneBy!
I don't understand it, bcz this example is copied from official documentation.
How I can execute DQL query in queryBuilder/createQuery?

Entity manager has a createQuery method.
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery($getQuery);
$items = $query->getResult();
Repository has a createQueryBuilder method.
$em = $this->getDoctrine()->getManager();
$qb = $em->getRepository(Item::class)->createQueryBuilder();
$query = qb->select('[columns]')->from('Entity')->where('[condition]')->getQuery();
$items = $query->getResult();

Related

Building a query to search for multiple attributes

I am very new to coding, especially with Symfony. But now my teacher has given me a task to create a query to search within 2 attributes. I have started writing the query, but there is still a lot lacking. I am wondering if someone can help, or send a link to help me finish it.
I need to make a search option which looks up into Artikelnummer and Omschrijving.
/**
* #Route("/artikel/zoek", name="zoekartikel")
*/
Public function zoek(Request $request){
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT a
FROM AppBundle:Artikel a
WHERE a.artikelnummer = input AND a.omschrijving LIKE input2'
);
$artikelen = $query->getResult();
return new Response($this->render('search.html.twig',
array('artikelen' => $artikelen)));
}
You need first to instantiate Result Mapping
use Doctrine\ORM\Query\ResultSetMapping;
$rsm = new ResultSetMapping();
Then
$query = $em-> createNativeQuery(
'SELECT a
FROM AppBundle:Artikel a
WHERE a.artikelnummer = ? AND a.omschrijving LIKE ?',
$rsm
);
$query->setParameter(1, 'input1'); // or var
$query->setParameter(2, 'input2'); // or var
$artikelen = $query->getResult();
return new Response($this->render('search.html.twig',
array('artikelen' => $artikelen)));
More docs here http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/native-sql.html

Doctrine- setting query parameters conditionally

I building application in Symfony 2.
I have to filter users basing on data passed in form.
I wrote something like this in my controller:
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb->addSelect('user');
$qb->from('Application\Sonata\UserBundle\Entity\User', 'user');
if(($filter['freelancer'])){
$qb->setParameters(array('freelancer' => $filter['freelancer']))
->andWhere('user.firstname = :freelancer');
}
if(($filter['category'])){
$qb->innerJoin('Flexihub\MainBundle\Entity\Category', 'category', 'WITH', 'user.category = category.id')
->setParameters(array('category' => $filter['category']))
->andWhere('user.category = :category');
}
$query = $qb->getQuery();
$result = $query->getResult();
dump($result);
Im stuck with error when im trying to pass both parameters.
Invalid parameter number: number of bound variables does not match number of tokens
What am I doing wrong?
Is there better solution to solve my problem?
It's logical to write it like this, so, first add criteria then provide arguments:
if(($filter['freelancer'])){
$qb
->andWhere('user.firstname = :freelancer')
->setParameter('freelancer', $filter['freelancer']);
}
if(($filter['category'])){
$qb
->innerJoin('Flexihub\MainBundle\Entity\Category', 'category', 'WITH', 'user.category = category')
->andWhere('user.category = :category')
->setParameter('category', $filter['category']);
}

doctrine not exists subquery

I have in a repository this code:
public function getNotAssignedBy($speciality, $diploma)
{
$qb = $this->createQueryBuilder('j')
->select('DISTINCT(j.id) id', 'j.firstName', 'j.lastName', 'j.dateBirth', 'j.sex')
->leftJoin('j.qualifications', 'q')
;
if ($speciality) {
$qb->andWhere('q.speciality = :speciality_id')->setParameter('speciality_id', $speciality);
}
if ($diploma) {
$qb->andWhere('q.diploma = :diploma_id')->setParameter('diploma_id', $diploma);
}
$result = $qb->getQuery()->getResult();
return $result;
}
How can I get only rows where id not exists in another entity ??
Any help. Thanks
You can achieve it with something like this:
....
// construct a subselect joined with an entity that have a relation with the first table as example user
$sub = $this->createQueryBuilder();
$sub->select("t");
$sub->from("AnotherEntity","t");
$sub->andWhere('t.user = j.id');
// Your query builder:
$qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));
Hope this help
Since I can't comment, so I will post a fixed version of #Matteo's solution
The correct way to use createQueryBuilder in this case is by using EntityManager. See my comment in the code below.
$sub = $this->_em->createQueryBuilder(); // _em stands for entity manager here. While $qb may use repositories createQueryBuilder() which requires alias
$sub->select("t");
$sub->from("AnotherEntity","t");
$sub->andWhere('t.user = j.id');
// Your query builder:
$qb->andWhere($qb->expr()->not($qb->expr()->exists($sub->getDQL())));

Sent leftjoin querybuilder rsult to twig

i have a leftjoin with doctrine querybuilder
$registros = $this->em->createQueryBuilder();
$registros->select('u,v')
->from('Entity\RegistroCam', 'u')
->leftjoin('Entity\CmMunicipios','v','WITH','u.camMunicipio = v.idMunicipio')
->orderBy('u.camPaterno', 'DESC');
$query = $registros->getQuery();
// Execute Query
$result = $query->getResult();
My problem is when I send the result to twig , it throws the following error
Twig_Error_Runtime: Method "idRegistro" for object "Entity\CmMunicipios" does not exist in "adminPanel.twig.html" at line 87
if i write
$registros->select('u')
works perfectly

Symfony2: How to convert 'Doctrine->getRepository->find' from Entity to Array?

I want to return an \Symfony\Component\HttpFoundation\JsonResponse with the record information, but I need to pass it as array.
Currently I do:
$repository = $this->getDoctrine()->getRepository('XxxYyyZzzBundle:Products');
$product = $repositorio->findOneByBarCode($value);
But now $product is an Entity containing all what I want, but as Objects. How could I convert them to arrays?
I read somewhere that I need to use "Doctrine\ORM\Query::HYDRATE_ARRAY" but seems 'findOneBy' magic filter does not accept such parameter.
*
* #return object|null The entity instance or NULL if the entity can not be found.
*/
public function findOneBy(array $criteria, array $orderBy = null)
Well thanks to dbrumann I got it working, just want to add it the full working example.
Also seems that ->from() requires 2 parameters.
$em = $this->getDoctrine()->getManager();
$query = $em->createQueryBuilder()
->select('p')
->from('XxxYyyZzzBundle:Products','p')
->where('p.BarCode = :barcode')
->setParameter('barcode', $value)
->getQuery()
;
$data = $query->getSingleResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
When you want to change the hydration-mode I recommend using QueryBuilder:
$query = $em->createQueryBuilder()
->select('p')
->from('Products', 'p')
->where('p.BarCode = :barcode')
->setParameter('barcode', $valur)
->getQuery()
;
$data = $query->getSingleResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
But what would probably be better, is adding a toArray()- or toJson()-method to your model/entity. This way you don't need additional code for retrieving your entities and you can change your model's data before passing it as JSON, e.g. formatting dates or omitting unnecessary properties.
Have done this two ways if you are working with a single entity:
$hydrator = new \DoctrineModule\Stdlib\Hydrator\DoctrineObject($entityManager);
$entityArray = $hydrator->extract($entity);
Last resort, you can just cast to an array like any other PHP object via:
$array = (array) $entity
NB: This may have unexpected results as you are may be working with doctrine proxy classes, which may also change in later Doctrine versions..
Can also be used:
$query = $em->createQueryBuilder()
->select('p')
->from('Products', 'p')
->where('p.BarCode = :barcode')
->setParameter('barcode', $valur)
->getQuery()
;
$data = $query->getArrayResult();

Categories