doctrine extra lazy load doesn't work as expected with count

前端 未结 2 2055
春和景丽
春和景丽 2021-02-09 16:41

I have an entity Shop and a related entity ShopProduct, with the following relation:

/**
 * @OR         


        
相关标签:
2条回答
  • 2021-02-09 17:31

    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 }}
    
    0 讨论(0)
  • 2021-02-09 17:39

    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(*)...

    0 讨论(0)
提交回复
热议问题