0

如何访问 Symfony2 学说 createQuery 结果的对象值?我想检索实体对象数组,而不是每个实体的 getId。

use MeetingBundle\Entity\Event;
class EventController extends Controller{
..
public function searchAction(Request $request){
...
 $em = $this->getDoctrine()->getManager();
 $searchArr= ['key1', 'key2'];
foreach ($searchArr as $val) { 
  $events = $em->createQuery( 'SELECT e FROM MeetingBundle:Event e
                   WHERE e.keywords LIKE  :keyw' )->setParameter('keyw', '%'.$val.'%')->getResult();

  foreach ($events as $event){
  print_r('<br>result <pre>'); print_r($event.getId()); print_r('</pre>');
//i am getting error, that i am calling undefined method getId()
  }
}

如果我尝试获取数组而不是对象,则可以访问 id:

    $events = $em->createQuery( 'SELECT e FROM MeetingBundle:Event e 
WHERE e.keywords LIKE  :keyw' )->setParameter('keyw', '%'.$val.'%')
->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
     foreach ($events as $event){
 print_r('<br>*id= <pre>'); print_r($event['id']); print_r('</pre>');
4

1 回答 1

0

必须使用:$event->getId() 而不是$event.getId()//给出控制器中未定义方法getId()的错误:调用未定义的函数MeetingBundle\Controller\getId()

但在 Doctrine 2 最佳实践中,实际上建议使用:->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);而不是使用->getResult();. http://www.uvd.co.uk/blog/some-doctrine-2-best-practices/

于 2015-12-11T12:01:06.310 回答