I'm using Doctrine in a project where I need data from multiple tables. In order to escape from N + 1 problem I'm fetching all the data, that I need before it go to the view. As I saw in the documentation the way to do this is to make a join with tables and then to call addSelect with the aliases of the joined table. The problem is that when I build the query that I need and call getResult, Doctrine returns me Collection of both entity objects and Proxies of the joined entity, which causes problems during the iteration of the array in the view, because Proxies don't have the same properties as the entity objects. I'm really confused of this behaviour. Can you help me in order to solve this issue?
You get proxy objects because they are lazy loaded which is correct. You shouldn't have got any problems with them, because when you iterate over collection all data should be set correctly. Proxies generally behave like fully loaded entity. If you have got problems, maybe problem is somewhere else. However you can set fetch to EAGER
in your relations to force build full entity.
@ManyToOne(targetEntity="target", fetch="EAGER")
@JoinColumn(name="target", referencedColumnName="id")
What's more you can use $query->getResult(Doctrine\ORM\Query::HYDRATE_ARRAY);
to hydrate all objects in query. You can try as well $queryBuilder->getQuery()->setHint (Query::HINT_FORCE_PARTIAL_LOAD, true)->get();
You can also load proxy object by yourself during iteration. Something like that
foreach($collection as $object) {
if ($object instanceof Doctrine\ORM\Proxy\Proxy) {
$object->__load();
}
}
However you may post your code (entities, query from repository and the view part) because there shouldn't be any problems with proxies.