我正在尝试从我的文章对象中选择我的文章,并加入评论作为本文评论数量的计数。所以我有这个版本:
$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"
}
}
知道这个查询的问题在哪里?
答案 0 :(得分: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 %}