How to retrieve an entity with all of its associations using EntityManager in Doctrine2?

前端 未结 4 520
夕颜
夕颜 2020-12-30 14:52

I have a simple entity with many-to-many and one-to-many associations. I\'m aware of \'Joins\' for fetching related associations which is a manual solution for my problem.

4条回答
  •  一向
    一向 (楼主)
    2020-12-30 15:38

    from http://doctrine-orm.readthedocs.org/en/latest/reference/dql-doctrine-query-language.html#temporarily-change-fetch-mode-in-dql

    you can set eager fetch mode temporarily:

    $query = $em->createQuery("SELECT u FROM MyProject\User u");
    $query->setFetchMode("MyProject\User", "address", "EAGER");
    $query->execute();
    

    If you want do load dynamically all associations with this fetch mode, you can use the getAssociationMappings() method of the Doctrine\ORM\Mapping\ClassMetadataInfo, passing your entity name as parameter to the constructor of ClassMetadataInfo and then iterate over the returned array as $assoc and call:

    $query->setFetchMode("MyProject\User", $assoc, "EAGER");
    

    Doc: ClassMetadataInfo#getAssociationMappings()

提交回复
热议问题