2

I'm trying to make a count request on an id field.

I have the following code in my controller:

$qb = $em->createQueryBuilder();
$qb->select('count(c.id)')
        ->from('MyBundle:Category', 'c')
        ->where('c.author = :aut')
        ->setParameter('aut', $author);

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

return $this->render('MyCategoryBundle:Category:categories.html.twig', array(
       'categories' => $categories,
       'result' => $result
    ));

And in my view.html.twig :

{% for category in categories %}      
       <li>
           {{ category.title }} 
           {% for total in  result %}
                {{ total }}
           {% endfor %}
      </li>          
{% endfor %}

It returns the category title and the string "Array" just besides. What am I doing wrong ?

2 Answers 2

3

The getResult() returns an array (collection) of objects. You have to use the getSingleScalarResult() function in order to get the result as a simple number.

Anyway, what is the goal of your code? If you want to display the number of categories for each author, your code may not work since you display a list of categories but you only count the categories from one author.

Sign up to request clarification or add additional context in comments.

3 Comments

Oh ok, I didn't knew that. Yes, I want to display the number of categories for one author. I get its id with the $author var.
So why do you use a for loop on the categories?
That was due to my array results using getResults(). I was wrong indeed. It works with getSingleScalarResult() and removing the loop in the view. Thanks for your help and explanation !
0

Try this:

$qb = $em->createQueryBuilder();
$qb->select('count(c.id) AS cnt')
        ->from('MyBundle:Category', 'c')
        ->where('c.author = :aut')
        ->setParameter('aut', $author);

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

and then in twig {{result.cnt}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.