Answer the question
In order to leave comments, you need to log in
How to properly cache data with relationships in Doctrine?
I am using Doctrine ORM in a Symfony2 project and setting up caching of database requests.
I set up result_cache_driver in the doctrine.orm config, and also created separate services for the cache (I use FilesystemCache).
For caching, I use two approaches:
1) the mechanism for caching query results built into the ORM:
$query = $this->em->createQuery('select a from AppBundle:Article a where a.id = :id')
->setParameter('id', $id)
->useResultCache(true, 0, $cacheKey);
$item = $query->getSingleResult();
if (($data = $cache->fetch($cacheKey)) === false) {
$data = doHardWork();
$cache->save($cacheKey, $data);
}
$query = $this->em->createQuery('select v from AppBundle:Video v where v.id = :id')
->setParameter('id', $id)
->useResultCache(true, 0, $cacheKey);
$item = $query->getSingleResult();
$this->em->createQuery('select m from ApplicationSonataMediaBundle:Media m where m.id = :id')
->setParameter('id', $item->getVideo()->getId())
->useResultCache(true)
->getSingleResult();
Answer the question
In order to leave comments, you need to log in
join-s unless explicitly set.
In general, I don’t see the point in your case of using the doctrine query cache if you already have your own caching layer.
ps It's not good to work with QueryBuilder in the controller, but if this case were in the service, then caching would not be a problem.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question