Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine - Get entity and relationships in one query

Am I missing a point with Doctrine? It's been very useful for some scenarios, but for the basic scenario of retrieving an entity using an Id (say using find() or findOneBy()) why do you see a query being fired off for every relationship to populate the main entity's properties?

Surely with the mapping/annotations I've created, Doctrine should be capable of a few joins and one query, without having to write a DQL query for the retrieval of each entity.

Or, as I'm predicting, have I missed the point somewhere!

like image 727
ste Avatar asked Nov 09 '12 20:11

ste


Video Answer


2 Answers

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

Let’s say, you have Book related one-to-many to Cover, and you want so select some books with their covers.

With query builder, use:

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

With query, use:

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

As the result, you will receive collections of Book with prepopulated $covers collection.

like image 110
Denys Popov Avatar answered Oct 21 '22 21:10

Denys Popov


Because the relationships are hydrated only when needed - by default Doctrine uses a lazy-loading strategy. If you already know that you will access the related entities, you should build a DQL query that retrieves the record AND the related entities.

like image 1
Roberto Avatar answered Oct 21 '22 21:10

Roberto