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

前端 未结 2 2061
春和景丽
春和景丽 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 }}
    

提交回复
热议问题