doctrine 2 findby function , get keys and values

dean jase picture dean jase · Sep 18, 2011 · Viewed 9k times · Source

can i get the keys and values dynamically.

in php, you would: foreach ($array as $key => $value)

but you can do this for :

$this->_em->getRepository('Members')->findBy(array('id' =>5));

any way to get the keys from this with their values..?

i can do this by turning it into an array and extract it but i wouldnt get any association results inside the array ..

i want to do this as i want to be able to extract all properties and values of this object and extract all other objects within it too..

Answer

Mehdi Fanai picture Mehdi Fanai · Sep 18, 2011

Ih had the same issue as you now have and after some research i just found a solution which you might be interested.what you need is an associative array of keys/values and not an object.findBy()method only returns entity OBJECT.so you will need to use DQL(doctrine query language).

//create a QueryBuilder instance
$qb = $this->_em->createQueryBuilder();
$qb->add('select', 'a')
//enter the table you want to query
->add('from', 'Members a')
->add('where', 'a.id = :id')
//order by username if you like
//->add('orderBy', 'a.username ASC')
//find a row with id=5
->setParameter('id', '5');
query = $qb->getQuery();
//if you dont put 3 or Query::HYDRATE_ARRAY inside getResult() an object is returned and if you put 3 an array is returned
$accounts = $query->getResult(3);

from doctrine documentation:

13.7.4. Hydration Modes

Each of the Hydration Modes makes assumptions about how the result is returned to user land. You should know about all the details to make best use of the different result formats:

The constants for the different hydration modes are: Query::HYDRATE_OBJECT Query::HYDRATE_ARRAY Query::HYDRATE_SCALAR Query::HYDRATE_SINGLE_SCALAR

To learn more about 'The Query Builder' please refer to doctrine2 documentation

Update: To fetch associated Entities you will need to define fetch joins.Here is an example provided in doctrine documentation:

$dql = "SELECT b, e, r, p FROM Bug b JOIN b.engineer e ".
   "JOIN b.reporter r JOIN b.products p ORDER BY b.created DESC";
$query = $entityManager->createQuery($dql);
$bugs = $query->getArrayResult();

foreach ($bugs AS $bug) {
  echo $bug['description'] . " - " . $bug['created']->format('d.m.Y')."\n";
  echo "    Reported by: ".$bug['reporter']['name']."\n";
  echo "    Assigned to: ".$bug['engineer']['name']."\n";
foreach($bug['products'] AS $product) {
  echo "    Platform: ".$product['name']."\n";}
  echo "\n";}

The code mentioned above will fetch your entities as array of arrays and you can do whatever you want with $keys and $values. Hope this helps...