doctrine额外延迟加载不能按预期工作

The*_*kie 6 symfony doctrine-orm twig

我有一个实体Shop和一个相关实体ShopProduct,具有以下关系:

/**
 * @ORM\OneToMany(targetEntity="ShopProduct", mappedBy="shopid", fetch="EXTRA_LAZY")
 */
private $products;
Run Code Online (Sandbox Code Playgroud)

在树枝模板,我想访问计数products,所以我访问

{{ entity.getProducts().count }}
Run Code Online (Sandbox Code Playgroud)

但是当使用symfony2探查器查看查询的数量和内容时,我发现发出了完整的选择,而不是COUNT我期望的(基于文档).

对每个Shops 发出完全选择会导致250Mb +的内存使用量和30+秒的页面加载时间,这是不希望的.

添加之后fetch="EXTRA_LAZY"我已经清除了学说缓存.

我是否忽略了某些东西,使用错误的方法或误解了文档?

[编辑]

doctrine/annotations                v1.1
doctrine/cache                      v1.0
doctrine/collections                v1.1
doctrine/common                     2.4.0-RC1
doctrine/data-fixtures              dev-master eef10f6
doctrine/dbal                       2.3.3
doctrine/doctrine-bundle            v1.2.0-beta1
doctrine/doctrine-fixtures-bundle   dev-master 275540d
doctrine/doctrine-migrations-bundle dev-master 99c0192
doctrine/inflector                  v1.0
doctrine/lexer                      v1.0
doctrine/migrations                 dev-master e1f6efc
doctrine/orm                        2.3.3
Run Code Online (Sandbox Code Playgroud)

Vig*_*jis 12

刚刚遇到同样的问题,解决方案非常简单:

{{ value.getAlerts.count() }}

代替

{{ value.getAlerts.count }}

Twig必须覆盖count()用于"Extra Lazy Load" 的Doctrine 方法,并使用它自己的实现的变体,它只是愚蠢地提取所有实体来计算它们.

这将所有预期的SELECT*查询转换为COUNT(*)...


Nic*_*ich 3

您没有使用 twig 的 count 函数,而是使用 php 内部的函数,如下所示。Twig 将逐一执行函数(首先调用 getProducts 导致加载所有产品,然后进行计数)。

{{ entity.getProducts().count }}
Run Code Online (Sandbox Code Playgroud)

getter 被自动调用,这意味着您可以只输出entity.products 并使用 twigs 内部长度过滤器来计算结果......但结果是相同的(获取所有产品)。

{{ entity.products|length }}
Run Code Online (Sandbox Code Playgroud)

您真正需要的是一种设置 ShopRepository 提供的 Shop 实体计数的方法。

public function findAllAddCount()
{
    $qb = $this->createQueryBuilder('s');
    $query = $qb
        ->set('s.productCount', $qb->expr()->count('s.products'))
        ->getQuery()
   ;

   return $query->getResult();
}
Run Code Online (Sandbox Code Playgroud)

...并将其添加到您的实体中:

protected $productCount;

public function getProductCount()
{
   return $this->productCount;
}

public function setProductCount($count)
{
    $this->productCount = $count;

    return $this;
}
Run Code Online (Sandbox Code Playgroud)

然后输出树枝中的产品数量,如下所示:

{{ entity.productCount }}
Run Code Online (Sandbox Code Playgroud)