Doctrine2 setFetchMode not working with "EAGER"
I also tried to extract related entities โwillinglyโ using setFetchMode in my request, but the following did not seem to work:
$query->setFetchMode("MyProject\User", "address", "EAGER");
When I jumped into the files, I found that the third parameter of $fetchMode should be an integer . Constants are defined in Doctrine \ ORM \ Mapping: ClassMetadataInfo. When transferring a string, Mapping\ClassMetadata::FETCH_LAZY used by default due to this if condition .
const FETCH_LAZY = 2; const FETCH_EAGER = 3; const FETCH_EXTRA_LAZY = 4;
Thus, setting the appropriate integer solved the problem:
$query->setFetchMode("MyProject\User", "address", 3);
Or declare a class with use Doctrine\ORM\Mapping\ClassMetadata at the top, and then use the constant:
$query->setFetchMode("MyProject\User", "address", ClassMetadata::FETCH_EAGER);
EDIT:
Since there seems to be a lot of confusion about the right choice of associations, I will edit my answer and add some additional information on how to get the union using my repository.
According to the documentation of the Doctrine, there are 2 types of compounds:
Conventional joins : used to limit results and / or calculate aggregate values.
Retrieve joins: in addition to regular joins: used to retrieve related entities and include them in the hydrated query result.
Thus, in order to get an entity that includes its associations, you will need to โconnectโ all these associations to make sure they are loaded with impatience.
I usually donโt use DQL queries to get entities and solve my selective joins; instead, I add my own method to the repository where I use the query designer. This is more flexible and much more readable than using DQL. The correct DQL query will be created by the query builder when the createQuery method is createQuery . You can check the created DQL query, of course, for debugging purposes.
An example of such a custom method in Patientprofile entities from the above question:
public function findPatientByIdWithAssociations($id)( // create a query builder for patient with alias 'p' $qb = $this->createQueryBuilder('p') ->where('p.id = :patient_id') ->addSelect('pd') ->leftJoin('p.documentation', 'pd') ->addSelect('pa') ->leftJoin('p.address', 'pa') ->setParameter('patient_id', $id); $query = $queryBuilder->getQuery(); return $query->getSingleResult(); }
And now you can use your own repository method to get the patient by identifier (for example, "555555557"), including links to the documentation and the address of the patient:
$repository = $this->em->getRepository('Entities\Patientprofile'); $patient = $repository->findPatientByIdWithAssociations('555555557');
Make sure you use both addSelect and leftJoin for leftJoin loading.