Symfony2 + Doctrine,试图计算连接表结果

时间:2017-04-15 16:38:51

标签: symfony doctrine-orm count doctrine

我在Symfony

中创建了这个查询
$qb = $em->createQueryBuilder('b')
        ->from('AppBundle:Blueprint', 'b')
        ->select('b, COUNT(v.id) as votecount')
        ->leftJoin('AppBundle:Vote', 'v', 'WITH', 'b.id = v.blueprint')
        ->groupBy('b.id')
        ->orderBy('votecount', 'desc')
    ;

这是我想要实现的查询

select *, COUNT(v.blueprint_id) as votecount from blueprint b
left join vote v on b.id = v.blueprint_id
where b.name like '%%'
group by b.id
order by votecount desc

当我试图访问twig中的Blueprint.name时,我收到以下错误:

键“0,votecount”的数组的键“name”不存在。

所以我将'b.name设为名称' 然后它继续为我尝试在树枝中访问的每个变量。 我是否真的必须为我尝试在树枝中渲染的每个变量设置别名?

我正在解决这个问题,因为已经花了2个小时,使用了很多在线资源,但我找不到解决这个非常简单的问题的方法。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是干编码的,但我希望它可以帮助您走上正轨:

在您的控制器中,例如

/**
* @Route("/", name="my_route")
* @Template("some_template.html.twig")
*/
public function myAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $qb = $em->createQueryBuilder('b')
            ->from('AppBundle:Blueprint', 'b')
            ->select('b, COUNT(v.id) as votecount')
            ->leftJoin('AppBundle:Vote', 'v', 'WITH', 'b.id = v.blueprint')
            ->groupBy('b.id')
            ->orderBy('votecount', 'desc')
        ;

    $blueprint_votes = $qb->getQuery()->getResult();

    return array(
        "blueprint_votes" => $blueprint_votes
    );
}

在您的模板中(some_template.html.twig):

<table>
    <thead>
        <tr>
            <th>Blueprint ID</th>
            <th>Blueprint Name</th>
            <th>Votes</th>
        </tr>
    </thead>
    <tbody>
        {%- for bv in blueprint_votes -%}
        <tr>
            <td>{{ bv[0].id }}</td>
            <td>{{ bv[0].name }}</td>
            <td>{{ bv['votecount'] }}</td>
        </tr>
        {%- endfor -%}
    </tbody>
</table>
相关问题