Force Doctrine to load related objects in JOIN

Question

What is the best way to force doctrine to load nested related objects from a JOIN request?

More details

I have several objects ( view, contentType, version, settings), with three levels of association:

view               (primary entity)
    contentType    (ManyToOne joined on view.contentTypeId = contentType.id)
    version        (OneToMany joined on version.viewId = view.id)
        settings   (OneToOne joined on settings.versionId = version.id)

I have a list that asks for all versions (do not view) to get the latest modified version. But I get access to properties from viewand contentTypeand settings. I access contentTypethrough view(so these are two levels in depth). When I refer to these properties in a loop, I don’t need Doctrine Lazy Loading each value with N queries for each loop.

So, I join the entity in the query and select all the fields.

$versionRepo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion');
$queryBuilder = $versionRepo->createQueryBuilder('e')
    ->join('e.view', 'view')
    ->addSelect('view')
    ->join('view.contentType', 'contentType')
    ->addSelect('contentType')
    ->join('e.settings', 'settings')
    ->where('e.siteId = :siteid')->setParameter('siteId', 1)
    ->setMaxLimit(25);

The first level ARE links are selected properly, for example. version.view. However, the doctrine handles it version.settingsas a lazy load, and I will have 25 additional queries, where it loads each individual value.

So, although I join settings, it's still a lazy download.

+4
source share
1 answer

If you want to avoid Lazy Loading (recommended for loops), Doctrine will offer you to join the entity during the request. But you must also add the object to the SELECT statement, for example.

->join('e.settings', 'settings')
->addSelect('settings')

From Doctrine on Join

SELECT . : "" "Fetch" ​​.

: / .

Fetch Joins: : .

DQL, . ( ) "" join ", SELECT DQL . " ".

Doctrine " , ".

$query->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);

-, , .

+7

All Articles