I have an entity Shop
and a related entity ShopProduct
, with the following relation:
/**
* @OR
You are not using twig's count function but the php internal one like this. Twig will execute the functions one by one ( first calling getProducts resulting in the load of all products , then count ).
{{ entity.getProducts().count }}
The getter is called automatically meaning you can just output entity.products and use twigs internal length filter to count the result ... but the result is the same ( fetching all products ).
{{ entity.products|length }}
what you're really looking for is a method setting the count on your Shop entity provided by the ShopRepository.
public function findAllAddCount()
{
$qb = $this->createQueryBuilder('s');
$query = $qb
->set('s.productCount', $qb->expr()->count('s.products'))
->getQuery()
;
return $query->getResult();
}
... and add this to your entity:
protected $productCount;
public function getProductCount()
{
return $this->productCount;
}
public function setProductCount($count)
{
$this->productCount = $count;
return $this;
}
Then ouput the product count in twig like this:
{{ entity.productCount }}
Just encountered the same problem and the solution was very simple:
{{ value.getAlerts.count() }}
instead of
{{ value.getAlerts.count }}
Twig must be overriding the Doctrine count()
method meant to "Extra Lazy Load" with a variant of it's own implementation that just dumbly fetches all entities to count them.
That turned all expected SELECT * queries into COUNT(*)...