1

我正在尝试从我的文章对象中选择我的文章并加入评论作为这篇文章的评论数量。所以我有这个构建:

$em = $this->getDoctrine()->getManager();
$query = $em->createQueryBuilder()
                ->select('a, COUNT(comments) AS comments_count')
                ->from('AcmeBlogBundle:Article', 'a')
                ->leftJoin('a.comments', 'comments')
                ->groupBy('a.id')
                ->orderBy('a.id', 'DESC');
$articles = $query->getQuery()->getResult();

但是我会尝试在我的 TWIG 模板中加载我的文章列表,我会收到这个错误:

Key "title" for array with keys "0, comments_count" does not exist in AcmeBlogBundle:Admin:index.html.twig at line 13

我的index.html.twig

  {% for article in articles %}
  <tr>
    <td>{{ article.title }}</td>
    <td><a href="{{ path('default_blog_show', {'slug' : article.slug}) }}">Visit</a> | <a href="{{ path('admin_blog_edit', {'article_id' : article.id}) }}">Edit</a> | <a href="{{ path('admin_blog_delete', {'article_id' : article.id}) }}" onclick="return confirm('Any question...');">Delete</a></td>
  </tr>
  {% endfor %}

但是,查询没问题,我在探查器中检查了它:

SELECT 
  a0_.id AS id0, 
  a0_.title AS title1, 
  a0_.slug AS slug2, 
  a0_.content AS content3, 
  COUNT(c1_.id) AS sclr4 
FROM 
  articles a0_ 
  LEFT JOIN comments c1_ ON a0_.id = c1_.article_id 
GROUP BY 
  a0_.id 
ORDER BY 
  a0_.id DESC

如果我尝试$articles使用\Doctrine\Common\Util\Debug::dump($articles);属性转储,我会得到这个结果:

array(1) {
  [0]=>
  array(2) {
    [0]=>
    string(30) "Acme\BlogBundle\Entity\Article"
    ["comments_count"]=>
    string(1) "0"
  }
}

知道这个查询结果的问题在哪里吗?

4

1 回答 1

2

这是因为教义返回了一组值。

在您的模板中使用它,它应该会看到标题:

<td>{{ attribute(article, 0).title }}</td>

编辑:

在你的树枝模板中试试这个:

  {% for item in articles %}
  {% set article = item[0] %}
  {% set comment_count = item['comments_count'] %}
  <tr>
    <td>{{ article.title }}</td>
    <td><a href="{{ path('default_blog_show', {'slug' : article.slug}) }}">Visit</a> | <a href="{{ path('admin_blog_edit', {'article_id' : article.id}) }}">Edit</a> | <a href="{{ path('admin_blog_delete', {'article_id' : article.id}) }}" onclick="return confirm('Any question...');">Delete</a></td>
  </tr>
  {% endfor %}
于 2013-10-17T15:48:52.163 回答