如何进行查询&在Symfony2和Doctrine2中查询关联实体的结果缓存


How to make query & result cache working for query of associated entity in Symfony2 and Doctrine2?

我使用memcahe作为Symfony Doctrine缓存驱动程序,如下所示:

doctrine:
    orm:
        metadata_cache_driver: memcache
        result_cache_driver: memcache
        query_cache_driver: memcache

我有ArticleTag实体,它们是manyToMany关系。我有一个控制器,它获取所有的文章(与分页),并将它们呈现给树枝。以下代码位于使用useQueryCache()useResultCache()Article存储库中:

$articles = $this->createQueryBuilder('a')
    ->orderBy('a.created_at', 'DESC')
    ->getQuery()
    ->useQueryCache(true)
    ->useResultCache(true)
    ->getResult();

这个DQL被完美地缓存为查询和结果,因为我没有看到在Symfony Profiler Doctrine小节中执行的查询。问题是关联实体Tag没有被缓存的结果。我在twig中有以下代码:

{% for article in articles %}
    // ...
    {% if article.tags|length %}
        <div class="tag-wrapper clearfix">
            {% for tag in article.tags %}
                // ...
            {% endfor %}
        </div>
    {% endif %}
    // ...
{% endfor %}

调用article.tags似乎总是在没有缓存的情况下获取相关文章的标签。在Symfony Profiler Doctrine部分中,我看到所有查询都在每次加载页面时执行。有可能缓存这个吗?

你错过了几件事:

  1. 你没有加入tags关系,也没有在你的查询
  2. 中选择它
  3. 你还需要启用急切抓取

看看这里的一些指针:Doctrine2 (Doctrine 2.1)在Symfony2中的动态加载

另一个注意事项,如果你预计在一个页面上有很多文章和很多标签,我将小心这样做。即使使用缓存,您也可能会遇到时间和/或内存问题。