无效的参数号:绑定变量的数量与 Doctrine 中的标记数量不匹配

2022-01-16 00:00:00 php mysql doctrine

使用 Doctrine 2 我想获取一些用户是另一个用户的联系人.user 表包含这些用户之间的映射.函数中的查询会返回如下错误:

Using Doctrine 2 I want to get some users that are contacts of another user. The table user contains the mapping between those users. The query in the function will return the following error:

参数号无效:绑定变量的数量与标记的数量不匹配.

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

但据我所知,$str 设置为b",$ownerId 设置为2",两者均由 setParameters函数.

However to my best understanding $stris set to "b" and $ownerId is set to "2" and both are assigned by the setParameters function.

 protected function getContactBySubstring($str, $ownerId) {
        echo $str;
        echo $ownerId;
        $em = $this->getDoctrine()->getEntityManager();
        $qb = $em->createQueryBuilder();
        $qb->add('select', 'u')
                ->add('from', 'PastonVerBundleEntityUser u, PastonVerBundleEntityContact 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;
    }

推荐答案

不要用引号将查询文本中的任何参数括起来!

Don't surround any of the parameters in your query text with quotes!

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

应该是

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

相关文章