简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM