Search code examples
symfonydoctrine-ormdoctrine-querysymfony-3.3

Symfony - Discard association field during hydration process of an EntityType querybuilder


My Symfony (3.3) Form EntityType is displayed as a select input and lists all the clients we have in database. The client entity is associated to several other entities using lazy mode.
When the select box is rendered, 204 DB queries are issued. I suspect the form component to call setters against each query result, resulting in the loading of many additional database queries.

We could set association mapping as "EAGER" I guess, or use join('…')->addSelect('…') methods inside the form's querybuilder option to force the datas to be part of the results, but the hydration process still costly when several entities are involved.
As you can see, I tried to use the Doctrine Query HINT, hoping it would solve the problem but It did not change anything.

Then, what is the way to go for such a use case ?
What should I do in order to only get the fields I need to populate the dropdown input ?

Here is what I tried so far:

    $builder->add('parent', EntityType::class, [
        'class' => Client::class,
        ,'required' => false
        ,'multiple' => false
        ,'query_builder' => function (EntityRepository $er) {
            $qb = $er ->createQueryBuilder('c')
            // All I want doctrine to fetch are the following fields
                ->select('PARTIAL c.{id,uuid,name,shortName}');
            // I expected this flag to help but it does not change the total amount of queries executed
            $qb->getQuery()->setHint(Query::HINT_FORCE_PARTIAL_LOAD, true);
            return $qb;
        }
    ])…

Thank you.


Solution

  • Solved

    One of the association is a oneToOne and is the only one which has its mapping "fetch" key set to 'EAGER'.
    I expected Doctrine to automatically join and select such an association when using the default EntityType's QueryBuilder, but it does not and I had to explicitly tell the querybuilder to do so (once again, despite the fetch flag set to 'EAGER').

        return $qb->select('c, p')->leftJoin('c.param', 'p');
    

    I don't really get the point here on what's going on underneath, still the number of database requests dropped down back to 4 queries.