简体   繁体   English

如何使查询和结果缓存可用于Symfony2和Doctrine2中的关联实体查询?

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

I'm using memcahe for Symfony Doctrine cache drivers as below: 我正在使用memcahe作为Symfony Doctrine缓存驱动程序,如下所示:

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

I have Article and Tag entities which are manyToMany relationship. 我有与manyToMany关系的ArticleTag实体。 I have a controller which fetches all articles (with pagination) and renders them to twig. 我有一个控制器,用于获取所有文章(带有分页)并将其呈现为细枝。 The below code is in Article repository that uses useQueryCache() and useResultCache() : 以下代码位于使用useQueryCache()useResultCache() Article存储库中:

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

That DQL is perfectly cached for query and result as I did not see the query executed in Symfony Profiler Doctrine section. 该DQL完美地缓存了查询和结果,因为我没有在Symfony Profiler教义部分中看到执行查询。 The problem is the result of the associated entity Tag not being cached. 问题是未缓存关联的实体Tag的结果。 I have the following code in twig: 我在树枝中有以下代码:

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

The call article.tags seems fetching the tags of the related article all the time without caching. 调用article.tags似乎总是在不缓存的情况下获取相关文章的标签。 I see all queries are executing on every page load in the Symfony Profiler Doctrine section. 我在Symfony Profiler原理一节中看到所有查询都在每次页面加载时执行。 Is it possible to cache this? 是否可以缓存它?

You're missing a couple of things: 您缺少两件事:

  1. you're not joining the tags relation and you're not selecting from it in your query 您没有加入tags关系,也没有从查询中选择tags关系
  2. you need to have eager fetching enabled as well for this to work 您还需要启用快速获取功能才能正常工作

Take a look here for some pointers: Doctrine2 (Doctrine 2.1) eager loading in Symfony2 . 看一下这里的一些指针: Doctrine2(Doctrine 2.1)渴望在Symfony2中加载

On another note, I'd be careful doing this if you anticipate a lot of articles with a lot of tags on that one page. 另一方面,如果您期望在该页面上有很多带有很多标签的文章,我会非常小心。 Even with caching, you might run into time and/or memory problems down the road. 即使使用缓存,您也可能会遇到时间和/或内存问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM