2012-04-16 77 views
1

使用Doctrine 2我想獲得一些用戶是另一個用戶的聯繫人。表user包含這些用戶之間的映射。函數中的查詢將返回以下錯誤:無效的參數編號:綁定變量的數量與Doctrine中的標記數量不匹配

Invalid parameter number: number of bound variables does not match number of tokens.

但是我最瞭解$str設置爲「b」和$ownerId被設置爲「2」,兩者都是由setParameters功能分配。

protected function getContactBySubstring($str, $ownerId) { 
     echo $str; 
     echo $ownerId; 
     $em = $this->getDoctrine()->getEntityManager(); 
     $qb = $em->createQueryBuilder(); 
     $qb->add('select', 'u') 
       ->add('from', '\Paston\VerBundle\Entity\User u, \Paston\VerBundle\Entity\Contact c') 
       ->add('where', "c.owner = ?1 AND c.contact = u.id AND u.username LIKE '?2'") 
       ->add('orderBy', 'u.firstname ASC, u.lastname ASC') 
       ->setParameters(array (1=> $ownerId, 2=> '%'.$str.'%')); 

     echo $qb->getDql(); 
     $query = $qb->getQuery(); 
     $users = $query->getResult(); 
     foreach($users as $user) 
      echo $user->getUsername(); 
     exit; 
     //return $contacts; 
    } 

回答

16

不要在查詢文本中用引號括住任何參數!

->add('where', "c.owner = ?1 AND c.contact = u.id AND u.username LIKE '?2'") 

應該使用QueryBuilder的

->add('where', "c.owner = ?1 AND c.contact = u.id AND u.username LIKE ?2") 
+10

我的情況有點不同。在我的情況下,我建立使用$ queryBuilder-> where(...) - > setParameters(...),但我需要使用andWhere(),因爲我有幾個動態添加的語句。 – Shawn 2013-03-27 13:47:15

相關問題