Doctrine - Get entity and relationships in one query

Did I miss the point with the Doctrine? This was very useful for some scenarios, but for the base scenario of retrieving an object using Id (say using find () or findOneBy ()), why do you see that the query is fired for each relationship to fill in the basic properties of the object?

Of course, with the creation / annotations I created, Doctrine should be capable of multiple joins and one query without having to write a DQL query to retrieve each object.

Or, as I predict, I missed a point somewhere!

+4
source share
2 answers

Just add the aliases of related objects to the select part of your query.

Lets say you have a one-to-many Book associated with Cover , and you want some books to have covers.

With the query builder, use:

 ->createQueryBuilder() ->select("book, cover") ->from("Book", "book") ->leftJoin("book.covers", "cover") 

With the request, use:

 SELECT book, cover FROM Book book LEFT JOIN book.covers cover 

As a result, you get Book collections with a pre-filled $covers collection.

+6
source

Because relationships only hydrate as needed, by default Doctrine uses a lazy loading strategy. If you already know that you will get access to related objects, you should create a DQL query that retrieves the record and related objects.

+1
source

Source: https://habr.com/ru/post/1445142/


All Articles