Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert the result of a query to an array of arrays

$shops = $this->em->getRepository('models\Shop')->findAll();

Gives my an array with entities but I need the entity as array.

How do I convert an entity to an array?

like image 239
PiTheNumber Avatar asked Nov 25 '11 13:11

PiTheNumber


2 Answers

Doctrine allows you to specify a hydration mode when executing queries, which let's you change the data type of the results returned. In this case, you need Query::HYDRATE_ARRAY. It does not let you specify this on the default findAll() method, found on the repositories. You will need to write your own DQL for it.

If you need a collection of entites as arrays:

$query = $em->createQuery('SELECT u FROM User u');
$entites = $query->execute(array(), Query::HYDRATE_ARRAY);

// If you don't have parameters in the query, you can use the getResult() shortcut
$query = $em->createQuery('SELECT u FROM User u');
$entities = $query->getResult(Query::HYDRATE_ARRAY);

If you need a single entity as an array, eg. for a specific ID:

$query = $em->createQuery('SELECT u FROM User u WHERE u.id = ?1');
$query->setParameter(1, $id);
$entity = $query->getSingleResult(Query::HYDRATE_ARRAY);

These methods are defined on Query, and AbstractQuery.

like image 197
K. Norbert Avatar answered Oct 24 '22 12:10

K. Norbert


I had the same issue.return get_object_vars($this) is not a good solution because it also converts internal doctrine object/properties too.After some research i found this class: EntitySerializer which creates clean array or JSON from your entities and removes unnecessary items.The documentation is located here.For example i used the following code:

$patientProfile = $this->em->getRepository('Entities\Patientprofile')->findOneByuserid('2222222');
$entitySerializer=new Bgy\Doctrine\EntitySerializer($this->em);
$patientProfile=$entitySerializer->toArray($patientProfile);
like image 31
Mehdi Fanai Avatar answered Oct 24 '22 12:10

Mehdi Fanai