Doctrine 2: Query result as associative array

前端 未结 5 1434
傲寒
傲寒 2020-12-29 05:58

In my Repository class I use the following code to query:

$query = $this->getEntityManager()->createQuery(\"
    SELECT s.term, COUNT(s.term) AS freq
          


        
5条回答
  •  余生分开走
    2020-12-29 06:32

    After lot of search I have found some solutions for doctrine object to array conversion. When we have associated objects in result.

    1.

    $person = $em->find('Person', 2);
    $da = array();
            $person = (array) $person;
            foreach($person as $i=>$d) {
                if (is_object($d)) {
                    $d = (array) $d;
                    foreach($d as $si=>$sd){
                        if (is_object($sd)) {
                            //var_dump('after convert array');
                            $da[$i][$si] = (array) $sd ;
                             //var_dump($da[$i][$si]);
                        } else {
                           $da[$i][$si] = $sd ;
                           //var_dump($da[$i][$si] );
                        }
                    }
    
                } else {
                    $da[$i] = $d;
                    //var_dump($da[$i]);
                }
            }
    
    echo '
    '; print_r($da); echo '
    '; exit;
    

    2.

    $query = $em->createQuery('SELECT w FROM  Person w WHERE w.Id = 2');
    $person = $query->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
    echo '
    ';  \Doctrine\Common\Util\Debug::dump($person); exit;
    

    3.

     $result = $em->createQueryBuilder();
                $person = $result->select('p')
                ->from('PsnPersonPsn', 'p')
                ->where('p.Id= 1')
                ->getQuery()
                ->getResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
                 echo '
    ';  \Doctrine\Common\Util\Debug::dump($person); exit;
    

提交回复
热议问题