Doctrine2使用setParameters

时间:2012-04-03 07:26:23

标签: sql symfony doctrine-orm

当我似乎在查询中使用参数时,我收到错误

  

参数号无效:绑定变量数与令牌数不匹配

这是我的代码

public function GetGeneralRatingWithUserRights($user, $thread_array)
{
    $parameters = array(
        'thread' => $thread_array['thread'],
        'type' => '%'.$thread_array['type'].'%'
    );

    $dql = 'SELECT p.type,AVG(p.value) 
        FROM TrackerMembersBundle:Rating p 
        GROUP BY p.thread,p.type';

    $query = $this->em->createQuery($dql)
        ->setParameters($parameters);

    $ratings = $query->execute();

    return $ratings;
}

如何正确配置参数数组?

2 个答案:

答案 0 :(得分:23)

您未在查询中包含参数。

$parameters = array(
    'thread' => $thread_array['thread'], 
    'type' => '%'.$thread_array['type'].'%'
);

$dql = 'SELECT p.type,AVG(p.value) 
    FROM TrackerMembersBundle:Rating p 
    WHERE p.thread=:thread 
    AND type LIKE :type 
    GROUP BY p.thread,p.type';

$query = $this->em->createQuery($dql)
    ->setParameters($parameters);

请参阅文档中的示例:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html#dql-select-examples

答案 1 :(得分:4)

感谢所有人的努力, 我使用querybuilder以不同方式使用它

        $parameters = array(
        'thread' => $thread_array['thread']
        ,'type' => $thread_array['type']
    );


    $qb = $this->em->createQueryBuilder();
    $query = $qb
        ->from('TrackerMembersBundle:Rating','rating')
        ->select(' rating.type,
        COUNT(rating.value) AS ratingcount ,
        AVG(rating.value) AS ratingaverage ')
        ->where(
        $qb->expr()->orx(
            $qb->expr()->eq('rating.thread', ':thread'),
            $qb->expr()->like('rating.type', ':type')
        )

    )
        ->groupBy('rating.thread,rating.type')
        ->setParameters($parameters)
        ->getQuery();