Symfony2: How to convert 'Doctrine->getRepository->find' from Entity to 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();