想象一下,我们有一个 ArrayCollection,包含多个 Country 的 Doctrine Entities 实例。还可以想象我的方法“getName()”实际上是与多种语言的一对多关系(A2lixTranslation 支持)......
关键是这个 ArrayCollection 是从 ElasticSearch 服务构建的,所以当我检索所有这些实体、迭代它们并打印它们的名称时,只是对每个类别的额外查询。
我真的不知道如何管理这种情况,所以 150 个额外的查询是不可维护的......
示例实现
$countries = // ArrayCollection of Countries, returned by any mapping system.
foreach ($countries as $country) {
/**
* As name is an entity, uses lazy loading in every iteration
* Because I get collection as it comes, I would like to retrieve
* all names in one query. I thought about perform a DQL with a join
* of all countries and their names, so Doctrine will catch'em all
* but only catch my query and results, and do not identify retrieved
* results with my collection, so is not working...
*/
$name = $country->getName();
echo $name;
}
// Could be nice do something like this...
$countries = // ArrayCollection of Countries, returned by any mapping system.
$queryBuilder = $this
->getDoctrine()
->getRepository('ProjectCoreBundle:Country')
->createQueryBuilder('c');
/**
* This query result should only add Cache with results
*/
$queryBuilder
->select('c','t')
->innerJoin('c.countryName','cn','WITH','c.id = cn.Country')
->getQuery()
->getResult();
foreach ($countries as $country) {
/**
* At this poing, as Name relation entity is already loaded and cached
* lazy load will simply return object ( Any query is performed )
*/
$name = $country->getName();
echo $name;
}