【问题标题】:Invalid parameter number: number of bound variables does not match number of tokens in Doctrine无效的参数号:绑定变量的数量与 Doctrine 中的标记数量不匹配
【发布时间】:2012-04-16 08:33:53
【问题描述】:

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

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

但据我所知,$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;
    }

【问题讨论】:

    标签: php mysql doctrine


    【解决方案1】:

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

    ->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")
    

    【讨论】:

    • 我的情况有点不同,使用查询构建器。在我的情况下,我使用 $queryBuilder->where(...)->setParameters(...) 构建,但我需要使用 andWhere() 因为我有一些动态添加的 where 语句。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多